Mithil Amin
Mithil Amin

Reputation: 207

How to send POST request to another node.js server

I make 2 servers

var express = require('express');
var querystring = require('querystring');
var http = require('http');

var app = express();
app.get('/', function (req, res) {
  var data = querystring.stringify({
    username: 'myname',
    password: 'pass'
  });

  var options = {
    host: 'localhost',
    port: 8081,
    path: '/demo',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(data)
    }
  };

  var httpreq = http.request(options, function (response) {
    response.setEncoding('utf8');
    response.on('data', function (chunk) {
      console.log("body: " + chunk);
    });
    response.on('end', function() {
      res.send('ok');
    })
  });
  httpreq.write(data);
  httpreq.end();
});

app.listen(8090, function(){
    console.log('Server start on 8090');
});

The second one is

var express = require('express');
var app = express();

app.post('/demo', function(req, res){
    console.log('Body : ', req.body);
});

app.listen(8081, function(){
    console.log('Server Start on 8081');
});

I want to send the data from localhost:8090 to the localhost:8081.

But at the 2nd server side when I try to print req.body It shows me

Server Start on 8081
Body :  undefined

Help me to find solution. And If you have better code then this then it will good for me.

Thank you for help in advance.

Upvotes: 1

Views: 3823

Answers (2)

peteb
peteb

Reputation: 19418

The reason why your body is undefined in your express server is because you're not using the body-parser middleware. Express cannot parse request body's for the Content-Type x-www-form-urlencoded like you have specified in your request. Also in your request you're not sending in data through the body of your request, you're sending it in the query string, so your Express Route needs to check the query string and not the body.

You'll need to make your Express look like this:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 1337;

app.use(bodyParser.urlencoded({ extended: true }); // Parse x-www-form-urlencoded

app.post('/demo', (req, res) => {
  console.log(`Query String: ${req.query}`);
  console.log(`Body: ${req.body}`);
});

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

Upvotes: 3

lithium_js
lithium_js

Reputation: 151

You can do request like this

require('request').post(
    "localhost:8081/demo", 
    {form: 
        {
            username: "name",
            password: "any"
        }
    },
    function(error, response, body){
        console.log(body);
    }
);

Upvotes: 0

Related Questions