RSA
RSA

Reputation: 1449

How to make a simple API for post method?

I have this code in Ionic app but I don't know how to make an API with Node.js to send this values to sever only by using Node.js.

submitForm() {
    let headers = new Headers(
      {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      });
    let options = new RequestOptions({ headers: headers });

    let data = JSON.stringify({
      Value1: this.form.value1,
      Value2: this.form.value2,
      Value3: this.form.value3
    });   
    console.log(data);

    let url = 'http://localhost:3000/calculate';
console.log(url);
    return new Promise((resolve, reject) => {
      this.http.post(url, data, options)
        .toPromise()
        .then((response) => {
          console.log('API Response : ', response.status);
          resolve(response.json());
        })
        .catch((error) => {
          console.error('API Error : ', error.status);
          console.error('API Error : ', JSON.stringify(error));
          reject(error.json());
        });
    });
  }

Upvotes: 0

Views: 245

Answers (2)

bobwirka
bobwirka

Reputation: 334

I've created an example Node.js project that illustrates client/server request/response using AJAX and JSON. It "requires" only 'http', 'path', and 'fs'.

It implements a 'calculate' function server-side, and has a web page that presents 3 input boxes and a 'Calculate' button.

It's on Github: "https://github.com/bobwirka/NodeClientServer.git"

Hope this will be of help.

Upvotes: 1

Arif Khan
Arif Khan

Reputation: 5069

You may like to use ExpressJS. Following example may help you

Create a directory lets called api with following 2 files

create app.js in api directory

var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


app.post('/calculate', function(req, res) {
    var data = req.body;
    console.log('Here are your data: ', data);
    res.json({message: 'you posted successfully'});
});


var port = process.env.PORT || 3000;
var server = http.createServer(app);
server.listen(port);
server.on('error', function(){
  console.error('Error')
});
server.on('listening', function(){
  console.log('server started on port ' + port)
});

create package.json file in api directory

{
  "name": "api",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "body-parser": "~1.17.1",
    "express": "~4.15.2"
  }
}

now open command line/terminal and install dependencies by running following command(you must go to inside api directory)

npm install

now you can run by just running either npm start or node app.js

You should google for learning and studying and post questions for bug/issue

Update: without any dependencies or library but not recommended

It will be better to use http framework like express, sailsjs, etc. but if you like to play with nodejs then following example may help you

var http = require('http');

var port = process.env.PORT || 3000;
var server = http.createServer(function(req, res) {
  var contentType = req.headers['content-type'];
  var rawData = '';
  req.on('data', function (chunk) {
    rawData += chunk;
  });
  req.on('end', function () {
    if(req.method === 'POST' && req.url === '/calculate' && contentType.indexOf('application/json')>-1){
      try {
        const data = JSON.parse(rawData);
        console.log('Your data is here: ', data);
        res.writeHead(200, { 'Content-Type': 'application/json'});
        var result = {message: 'you have posted successfully'}
        res.end(JSON.stringify(result));
      } catch (e) {
        console.error(e.message);
        res.writeHead(400, { 'Content-Type': 'application/json'});
        var result = {message: e.message}
        res.end(JSON.stringify(result));
      }
    } else {
      res.writeHead(404, { 'Content-Type': 'application/json'});
      var result = {message: 'Url not found'}
      res.end(JSON.stringify(result));
    }
  });
});
server.listen(port);
server.on('error', function(){
  console.error('Error')
});
server.on('listening', function(){
  console.log('server started on port ' + port)
});

Upvotes: 2

Related Questions