I am trying ti write a sample POST call in express.
var express = require("express")
, app = express()
, server = require('http').createServer(app)
, bodyParser = require('body-parser');
app.listen(80, function() {
console.log("server started");
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.post("/test", function(req, res) {
try {
console.log(req.body);
res.send("working " + req.body.name);
} catch(e) {
console.log("error in test API" + e.message);
res.end();
}
});
But I am unable to access body data on the server. It is empty. Below is postman query.
2 Answers 2
Select raw under body in Postman, not form-data if you want JSON data.
Then enter the data in JSON format. Postman should format it if you have the header set: Content-Type: application/json
Edit:
If you want to parse form-data you can't use body-parser as stated in the readme:
This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
- busboy and connect-busboy
- multiparty and connect-multiparty
- formidable
- multer
To read as req.body you're missing the Content-Type : application/json header I think, add it and make the request into a raw json. Or else youre getting a string and cannot directly access it as req.body
eg :
{"name" : "abcd"}
(削除) Update :
If you need Form data use the bodyParser to convert text to json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
(削除ここまで) Update 2 :
It seems the issue is with multipart/form-data you're using. To handle it you would need a specific framework like multer due to security issues. The below should work.
var multer = require('multer');
var upload = multer() ;
app.post('/test', upload.array(), function (req, res, next) {
console.log(req.body);
});
3 Comments
multer will work. I used that in separate project. In this form data there is no multipart data I guess. So why body-parser is not working.
{}