Search code examples
node.jsexpressfetch

Node express req.body returns empty obj


Here is my fetch request in the client side

let data = JSON.stringify({
  "username": "test",
  "password": "test"
 });

 let response = await fetch("http://localhost:5050/api/login", {
  method: 'post',
  body: data
})

In node server, this is what I had for login

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


router.post('/login', function(req, res) {
  console.log(req.body) // Returns {}
  res.json(JSON.stringify({success: "qwer123qwer324135142534123qwerqwersfg"}));
})

While print req.body returns {}. Can anyone know how to solve it?

Update

I tried the same thing using postman. It prints the correct object in the node server. But while using fetch only it fails.

Package.json

"dependencies": {
   "body-parser": "^1.19.0",
   "cors": "^2.8.5",
   "express": "^4.17.1",
   "mongoose": "~3.6.13"
 }

Solution

  • Fetch API by default sets Content-Type for request to text/plain and in this case since server API accepts JSON data, we need to explicitly set content type header. Changing code for fetch to following should get it to working:

     let response = await fetch("http://localhost:5050/api/login", {
      method: 'POST',
      body: data,
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
    })
    

    NOTE: (This does not impact data received in request handler but as general practise)

    Also in server code, there is not need to include both body-parser / express middleware for json parsing. You can either use:

    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded(<options>))
    
    

    OR

    app.use(express.json());
    app.use(express.urlencoded(<options>));
    
    

    No need to include both. You can read more about this in following stackoverflow post: https://stackoverflow.com/a/47232318/2235057