POST Method in Rest API in Express


Create LearnExpressJSRestAPIWithRealApps folder and select to this folder in Visual Studio Code

Use the following command to install Express.JS:

npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save

Create a new folder named api inside the server project. Create demo.api.js file inside api folder contains Rest APIs insert new data from client

var DemoAPI = {
    create: function (request, response) {
        console.log('New Product Info');
        console.log('Id: ' + request.body.id);
        console.log('Name: ' + request.body.name);
        console.log('Price: ' + request.body.price);
    }
};

module.exports = DemoAPI;




Inside the api folder create a new file named index.js. This file will hold all the routes needed for rest api in server.

var express = require('express');
var router = express.Router();

var DemoAPI = require('./demo.api');

router.post('/demo/create', DemoAPI.create);

module.exports = router;

At the root of server project, create a file named server.js. This will be the entry point into node application. This will start the server and listen on a local port

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.use('/api', require('./api/index'));

var server = app.listen(9090, function () {
	var host = server.address().address;
	var port = server.address().port;
	console.log("Server listening at http://%s:%s", host, port)
 });





Create LearnExpressJSRestAPIWithRealApps_Client folder and select to this folder in Visual Studio Code

Use the following command to install http module

npm install http --save

Create a new folder named api inside the client folder. Create demo.api.js file inside api folder contains method call Rest API from server

var http = require('http');

var DemoAPIClient = {
    create: function (product, callback) {
        var options = {
            hostname: 'localhost',
            port: 9090,
            path: '/api/demo/create',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        };

        var post_request = http.request(options, function (response) {
            response.on('end', function () {
                callback({
                    status: response.statusCode
                });
            });
            response.on('error', function (error) {
                callback({
                    status: response.statusCode,
                    error: error.message
                });
            });
        });

        post_request.write(JSON.stringify(product));
        post_request.end();
    }
};

module.exports = DemoAPIClient;




At the root of client project, create a file named client.js. This will call Rest API and display results

var DemoAPIClient = require('./api/demo.api');

var product = {
    id: 'p01',
    name: 'name 1',
    price: 20
};

DemoAPIClient.create(product, function (result) {
    if (result.error) {
        console.log(result.error)
    } else {
        console.log('Status: ' + result.status);
    }
});

Output from Client

Status: 200

Output from Server

New Product Info
Id: p01
Name: name 1
Price: 20