JSON data in the request body is not processed using body-parser

When I send a POST request using the mail manager to localhost: 8080 / api / newUser with the request body:

{name: "Harry Potter"}

At the end of the server, console.log (req.body) prints:

{ '{name: "Harry Potter"}': '' }

server.js

var express = require('express'); 
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');

app.use('/', express.static(__dirname));

router.use(function(req, res, next) {
    next();
});

router
    .route('/newUser')
    .post(function(req, res) {
        console.log(req.body);
    });

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
app.use('/api', router);

app.listen(8080);

What am I doing wrong?

+4
source share
2 answers

In express.js, the order in which you declare the middleware is very important. bodyParsermiddleware must be defined earlier than your own middleware (api endpoints).

var express = require('express'); 
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');

app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies

router
    .route('/newUser')
    .post(function(req, res) {
        console.log(req.body);
    });

app.use('/api', router);

app.listen(8080);
+4
source

Change request header

'Content-Type': 'application / JSON'

So bodyParser can analyze the body.

* , . angular 5 (body-parser)

+3

All Articles