javascriptnode.jshttppostexpress

How to send a POST request from node.js Express?


Could someone show me the simplest way to send a post request from node.js Express, including how to pass and retrieve some data? I am expecting something similar to cURL in PHP.


Solution

  • var request = require('request');
     function updateClient(postData){
                var clientServerOptions = {
                    uri: 'http://'+clientHost+''+clientContext,
                    body: JSON.stringify(postData),
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
                request(clientServerOptions, function (error, response) {
                    console.log(error,response.body);
                    return;
                });
            }
    

    For this to work, your server must be something like:

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json())
    
    var port = 9000;
    
    app.post('/sample/put/data', function(req, res) {
        console.log('receiving data ...');
        console.log('body is ',req.body);
        res.send(req.body);
    });
    
    // start the server
    app.listen(port);
    console.log('Server started! At http://localhost:' + port);