Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to make an http POST request in node.js

    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 366
    Comment on it

    I have a situation in which I have to make an post  http request to another server and get the http request data(If it exist) and then on the basis of data do further calculation. I have to also put the check that if there is any delay on the response then abort the http request and throw the error.So I can explaining this by giving a simple example step by step.

     

    Step 1:  First install http module by which we will send http request.
     

    npm install --save http

     

    Step 2: Then we will require the module where we want to use.

     

    var http = require('http');

     

    Step 3: Now we will write the code to do http request in node.js. Start with routes.js
     

    router.post('/saveMeeting', meetingController.saveMeeting);
    
    router.post('/meetingData', meetingController.calendarId);

     

    Step 4: Now we write the code for making http post request.

     

    //Check meeting response
    module.exports.saveMeeting = function(request, response){
        var meetingData=request.body;
        getMeetingRequestData(meetingData,function(err,meetingDatacallback){
            if(err) throw err;
            else{
                if(meetingDatacallback==null || meetingDatacallback=='' || meetingDatacallback=='undefined'){
                    responseResult='fail';
                }else{
                    responseResult='Success';
                }
                response.json({
                  Success: true,
                  message: 'Meeting Response',
                  meetingDataResponse:responseResult
                }); 
            }
            
        });
    }
    
    //Function to send the http request and send the response back where we want.
    
    function getMeetingRequestData(meetingData,callback) {
        data=meetingData;
        var requestPerameter={
            host : 'localhost',
            port : 7000,
            path : '/' +meetingData.calendarId, // the rest of the url with parameters if needed
            method : 'POST' // do POST
        }
        var requestData = http.request(requestPerameter, function(res) {
            // explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)
            res.setEncoding('utf8');
            // incrementally capture the incoming response body
            var appendStringData = '';
            res.on('data', function(chunk) {
                appendStringData += chunk;
            });
            // do whatever we want with the response once it's done
            res.on('end', function() {
                try {
                    parseData=appendStringData;
                } catch (err) {
                    console.error('Unable to parse response as JSON', err);
                    return callback(err,null);
                }
                // pass the relevant data back to the callback
                callback(null,parseData);
            });
    
        }).on('error', function(err) {
            // handle errors with the request itself
            console.error('Error with the request:', err.message);
            callback(err,null);
        });
        //After 3 sec the request will automatically terminate
        requestData.setTimeout(0, function() {
            console.log('Request timeout');
            requestData.abort();
        });
        requestData.on('error', function(err) {
            console.error('Request timeout', err);
            return callback(err,null);
        });
        requestData.end();
        
    }

     

    Here In the above code we can see first it will go the saveMeeting function then we have call a another function getMeetingRequestData function and pass callback in this function. In getMeetingRequestData function we have send calendarId in post method and it will go to the another server and get data from there we will receive data data in chunk so we will append our data in string and so now we have the data .Now we will do any operation with the data.

     

    So by the above example and explanation it is clear that "How to make an http POST request in node.js".

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: