Reputation: 3325
I have the following code:
var express = require('express');
var app = express.createServer();
var request = require('request');
app.use(myMiddleware);
app.listen(5010);
var payload = { id: 1 };
request({
method: 'POST',
body:JSON.stringify(payload),
url: 'http://localhost:5000'
}, function(err, res, body) {
console.info("Request Done");
})
In my middleware code I want to parse the body and extract the request id, yet for some reason the following code doesn't work (payload is undefined):
var myMiddleware= function (req, res, next){
var payload = req.body;
if (payload.id === 1) console.info("first request!!!!!");
next();
}
When I try to print "payload" all I get is [object Object]
.
Could you please tell me how to extract the id, and how to print the attributes of the payload object?
Thanks, Li
Upvotes: 2
Views: 6406
Reputation: 3325
Solved by adding:
app.use(express.bodyParser());
and by adding the following to the request code:
json: true
After adding the json=true attribute I also removed JSON.stringify(...) from the body of the request (now I don't need to stringify the body since it expects a json object)
Thanks.
Upvotes: 3