0

I am having trouble reading parameters from the request body for a post request i know this has been asked several times but all the answer are saying to call the body parser before calling app.use() for the routes i did this and also called bodyparser.urlencode() and and it's still giving me undefined whenever i console.log(req.body) or just prints {} ( an empty object)

this is my code

const bodyParser=require('body-parser');
const express=require('express');
const app=express();
app.use(
   bodyParser.urlencoded({
     extended: false
   })
 )

 app.use(bodyParser.json())

 app.post('/endpoint', (req, res) => {
   console.log(req.body);
   res.status(400).send({ "ReturnMsg": "User Already Exits" });
 })

 // the port where the application run
const port = process.env.PORT || 6001;
app.listen(port, () => console.log(`Listening on port ${port}...`));

1 Answers1

1

So form-data is NOT supported by body-parser, generally multipart/form-data(the mime type of form-data) is used to upload files. Most API related cases JSON or XML is used, and when you post a <form> from HTML it generally gets sent as application/x-www-form-urlencoded.

A one line excerpt from application/x-www-form-urlencoded or multipart/form-data?:

Summary; if you have binary (non-alphanumeric) data (or a significantly sized payload) to transmit, use multipart/form-data. Otherwise, use application/x-www-form-urlencoded.

Now, to POST from Postman,

Change the settings to either x-www-form-urlencoded or raw->then select JSON from the dropdown

Example

Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35