Sample 'Advanced REST Client' Request
I'm using Postman and Advanced REST client to create a basic POST request for the following code -
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http');
// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
//app.listen(6666);
http.createServer(function (req, res) {
h2s(req, res);
}).listen(6666, '127.0.0.1');
console.log('Server running at http://127.0.0.1:6666/');
module.exports = function h2s(req, res) {
console.log("inside h2s");
app.use(function (req, res) {
console.log("req.body : " + req.body);
res.send("OK");
});
}
But, when I debug, I find that req.body is missing in the "req object tree". What's more strange is all the changes that I make to req.headers are available in the req object tree.
Looks like I seem to be making a trivial mistake, but I'm unable to figure it out. Been trouble-shooting for an hour or so but no luck!
Can anyone of you figure out why req.body seems to be missing from the req object tree?
Will be of great help to me. Thanks!
It looks like you have several issues in your code:
instead of
http.createServer(function (req, res) {
h2s(req, res);
}).listen(6666, '127.0.0.1');
console.log('Server running at http://127.0.0.1:6666/');
module.exports = function h2s(req, res) {
console.log("inside h2s");
app.use(function (req, res) {
console.log("req.body : " + req.body);
res.send("OK");
});
}
For creating the server, try
http.createServer(app).listen(8000, '127.0.0.1'); //using http
Or (using express directly)
app.listen(8000,function(){
console.log('Server running at http://127.0.0.1:8000/');
});
Then register an handler function for your requests, there you can access req.body
app.use(function (req, res) {
console.log("req.body : " + req.body);
res.send("OK");
});
Dear u set body parser Url Encoding to true
// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
extended: true
}));
and check by printing the req.body, it work for me and might for u also
the req.body can be accessed also when
content-type:"application/x-www-form-urlencoded"
read this
In your case , your content-type is application/json"
so try changing the content-type to "application/x-www-form-urlencoded"
also url encode the parameters while sending to the server from JS
also solution can be
// fire request
request({
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: JSON.stringify(requestData)
}, ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.