Can't get POST data using NodeJS/ExpressJS and Postman

浪子不回头ぞ 提交于 2019-11-30 18:42:31
R. Gulbrandsen

Add the encoding of the request. Here is an example

..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
..

Then select x-www-form-urlencoded in Postman or set Content-Type to application/json and select raw

Edit for use of raw

Raw

{
  "foo": "bar"
}

Headers

Content-Type: application/json

EDIT #2 Answering questions from chat:

  1. why it can't work with form-data?

You sure can, just look at this answer How to handle FormData from express 4

  1. What is the difference between using x-www-form-urlencoded and raw

differences in application/json and application/x-www-form-urlencoded

Goutam Ghosh
let express = require('express');
let app = express();

// For POST-Support
let bodyParser = require('body-parser');
let multer = require('multer');
let upload = multer();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/api/sayHello', upload.array(), (request, response) => {
    let a = request.body.a;
    let b = request.body.b;


    let c = parseInt(a) + parseInt(b);
    response.send('Result : '+c);
    console.log('Result : '+c);
});

app.listen(3000);

Sample JSON and result of the JSON:

Set Content-typeL application/JSON:

I encountered this problem while using routers. Only GET was working, POST, PATCH and delete was reflecting "undefined" for req.body. After using the body-parser in the router files, I was able to get all the HTTP methods working...

Here is how I did it:

...
const bodyParser = require('body-parser')
...
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
...
...
// for post
router.post('/users', async (req, res) => {
    const user = await new User(req.body) // here is where I was getting req.body as undefined before using body-parser
    user.save().then(() => {
        res.status(201).send(user)
    }).catch((error) => {
        res.status(400).send(error)
    })
})

For PATCH and DELETE as well, this trick suggested by user568109 worked.

On more point I want to add is if you created your project through Express.js generator in your app.js it also generates bellow code

app.use(express.json());

if you put your body-parser above this code the req.body will return null or undefined you should put it bellow the above code see bellow for correct placement

 app.use(express.json());
 app.use(bodyParser.urlencoded({extended:true}));
 app.use(bodyParser.json());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!