'node.js express req.body undefined
var express = require('express');
var app = express();
var PORT = 3000;
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}));
app.post('/', function (req, res) {
console.log(req.body);
console.log(req.body.username);
res.end();
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Test by postman: Post: http://localhost:3000 { "username":"userabc", "password":"passwd1234" }
But, the result is: {} undefined
Solution 1:[1]
Try setting Content-Type: application/json in the request headers
Solution 2:[2]
You need to set Content-Type as application/json on the request.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Luis Jose Torres Muñoz |