Search code examples
node.jsrestexpressmiddlewarebody-parser

Body parsers behaving weirdly


I am trying to develop an app with few APIs, the issue I am facing here is when I use

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

as my middleware, it doesnt intake the requests i send through postman (all the request sent through postman goes with empty body idk why. And it takes all the requests sent via html form.

On the other hand, if I use

app.use(express.json({extended: false}))

as my middleware to parse json objects, it takes all the requests from postman but doesnt take requests from my browser form. Can anyone explain whats happening here?


Solution

  • In order for express to be able to parse both JSON request payloads and simple form-data requests, you simply need to setup both of the mentioned middlewares (note that express.json() does not have an extended option):

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

    See the docs for more information:

    https://expressjs.com/en/api.html#express.json https://expressjs.com/en/api.html#express.urlencoded