42

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.

Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100
  • 2
    [Use `request`](http://stackoverflow.com/a/28297185/1377002). – Andy Sep 01 '15 at 09:25
  • 1
    see this http://stackoverflow.com/questions/6819143/curl-equivalent-in-nodejs – Muhammad Usman Sep 01 '15 at 09:26
  • Possible duplicate of [How to make an HTTP POST request in node.js?](http://stackoverflow.com/questions/6158933/how-to-make-an-http-post-request-in-node-js) – AechoLiu Apr 13 '17 at 06:48
  • In Node.js 18, the fetch API is available on the global scope by default https://stackoverflow.com/questions/6158933/how-is-an-http-post-request-made-in-node-js/71991867#71991867 – Abolfazl Roshanzamir Apr 24 '22 at 20:04

6 Answers6

27
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);
Gautam
  • 743
  • 7
  • 9
7

you can try like this:

var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
               , url: <your URL>, body: <req_body in json> }
               , function(error, response, body){
   console.log(body); 
}); 
Vinod Poorma
  • 419
  • 1
  • 6
  • 15
6

As described here for a post request :

var http = require('http');

var options = {
  host: 'www.host.com',
  path: '/',
  port: '80',
  method: 'POST'
};

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();
dvhh
  • 4,724
  • 27
  • 33
  • wow with streams, callbacks, and such things get out of hand fast. It almost feels like working in C – Muhammad Umer Jun 30 '17 at 01:19
  • @MuhammadUmer I think thing are getting simpler regarding callback, if you use promise interface. I never used this module but there is a `request-promise` which implement promise over the request object – dvhh Jun 30 '17 at 02:50
6

in your server side the code looks like:

var request = require('request');

app.post('/add', function(req, res){
  console.log(req.body);
  request.post(
    {
    url:'http://localhost:6001/add',
    json: {
      unit_name:req.body.unit_name,
      unit_price:req.body.unit_price
        },
    headers: {
        'Content-Type': 'application/json'
    }
    },
  function(error, response, body){
    // console.log(error);
    // console.log(response);
    console.log(body);
    res.send(body);
  });
  // res.send("body");
});

in receiving end server code looks like:

app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});

Schema is just two properties unit_name and unit_price.

Corentin Houdayer
  • 988
  • 2
  • 8
  • 19
Sunilkumar A
  • 111
  • 1
  • 3
4

I use superagent, which is simliar to jQuery.

Here is the docs

And the demo like:

var sa = require('superagent');
sa.post('url')
  .send({key: value})
  .end(function(err, res) {
    //TODO
  });
teik
  • 508
  • 4
  • 26
0

Try this. It works for me.

const express = require("express");
const app = express();
app.use(express.json());
const PORT = 3000;

const jobTypes = [
{ id: 1, type: "Interior" },
{ id: 2, type: "Etterior" },
{ id: 3, type: "Roof" },
{ id: 4, type: "Renovations" },
{ id: 5, type: "Roof" },
];

app.post("/api/jobtypes", (req, res) => {
const jobtype = { id: jobTypes.length + 1, type: req.body.type };
jobTypes.push(jobtype);
res.send(jobtype);
});

app.listen(PORT, console.log(`Listening on port ${PORT}....`));