Stuart Fong
Stuart Fong

Reputation: 633

Express receiving empty req.body

When I call a fetch post request:

fetch('http://localhost:3001/insertUser', {
            method: 'POST',
            mode: "no-cors",
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ a: 1 })
        }).then(res => {
            console.log(res)
        }).then(err => {
            console.log(err)
        })

and receive it on the server with:

const path = require("path")
const express = require("express")
const bodyParser = require('body-parser');

const app = express()

require('dotenv').config();

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

app.post("/insertUser", (req, res) => {
    console.log(req.body)
})

app.listen(process.env.PORT || 3001, () => {
    console.log("Listening on port 3000");
}); 

I get an empty object, even though I am trying to send

{
    a:1
}

I have

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

included in my server file and also tried changing the fetch mode to be cors instead of no-cors

package.json:

{
  "name": "progression-tracker-server",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "env": "0.0.2",
    "express": "^4.17.1",
    "mongodb": "^3.6.3",
    "mongoose": "^5.11.8"
  }
}

Upvotes: 0

Views: 193

Answers (1)

jfriend00
jfriend00

Reputation: 707218

The problem is caused by the no-cors option. If you remove that, then it works for me when I reproduce the code you show.

The reason for that is that no-cors only allows a limited set of headers and does not allow a content-type of application/json like you are trying to use. So, presumably that content-type is stripped by the browser and thus your bodyparser middleware does not match and doesn't do its job so the body of the post is never read and req.body ends up empty.

So, to make that type of request, you need to remove the no-cors option and if it is a cross origin request, then you need to enable that specific type of CORs request in your server or change your struture so that request isn't cross origin.

Upvotes: 1

Related Questions