1

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"
 }
Mari Selvan
  • 3,598
  • 3
  • 21
  • 36
  • 2
    Are you using middleware (`app.use()`) such as body-parse to parse the body? – Nick Parsons Feb 01 '21 at 08:36
  • Can you please share code of body-parser middleware that you might have included in app.js file? If it works via postman and not via fetch then there are chances that we might need to update options set in middleware. It won't be possible to help without looking at middleware code. – Raeesaa Feb 01 '21 at 10:15

3 Answers3

1

You need to use a middleware in order to parse the body:

Add in your app:

app.use(express.json());
Naor Levi
  • 1,713
  • 1
  • 13
  • 27
1

just try like this in app.js

const bodyParser = require('body-parser');


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

Mohammad Yaser Ahmadi
  • 4,664
  • 3
  • 17
  • 39
1

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

Raeesaa
  • 3,267
  • 2
  • 22
  • 44