Reputation: 1341
I am using the request package in Nodejs to send a post request to another Nodejs server:
var options = {
method: 'POST',
url: 'http://12.12.12.12:3230/',
headers: { 'Content-Type': 'application/json' },
body: {
Num:1212,
Cust:'TEST'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
// Process the body and return the response.
// return res.send(body);
});
In my another Nodejs Server:
app.post("/",(req,res)=>{
console.log(req.body.Num)
console.log(`Someone sent a post request`)
})
My second Nodejs server, where I am listening for POST request displays the following in the console:
undefined
Someone sent a post request
How do I receive the value of the post request in this case?
Upvotes: 0
Views: 70
Reputation: 13
You can have a look at bodyParser middleware in express
https://www.npmjs.com/package/body-parser
Upvotes: 0
Reputation: 2401
make sure to add bodyParser in your backend middleware, something like:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
and require it on top like:
const bodyParser = require('body-parser');
hope this helps :)
Upvotes: 1
Reputation: 410
You also need to use a body parsing middleware above all routes such as express.json(), ie:
app.use(express.json())
Upvotes: 0
Reputation: 782407
You need to convert the body to JSON.
body: JSON.stringify({ Num:1212, Cust:'TEST' }),
Upvotes: 0