expresspostbody-parser

Processing JSON post request on express. Followed all suggestions but empty request body


I am using the following to post to my express server from a React App:

const response = await fetch('http://localhost:3100/api', { 
  method: 'POST',
  mode: 'no-cors',
  headers: {
    'Content-type': 'application/json'
  }, 
//  body: { "user":"1", "cmd":"Send NFT"},
  body: JSON.stringify({ user: 1, cmd:"Send NFT"}),
          })

I tried to use either one of the body formats

And on the nodejs side with version 4.21.1 express:

const express = require('express');
const app = express();
const port = 3100;

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Hello World!');
})

app.post('/api', (request, response) => {

  console.log("User: " + JSON.stringify(request.body) );
  
  if (request.body.user == 1) response.send(JSON.stringify({ user: 1, cmd: request.body.cmd}));
  else if (request.body.user == 2) response.send(JSON.stringify({user: 2, cmd: "Info from 1"})); 
})
  
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

I get "User: {}"

I'm thinking this is a result of CORB protection, but as far as I can tell, the principal ways to help properly evade unwanted filtering is to properly label the content type, in this case,

headers: {'Content-type':'application/json'}

I had to mark the fetch as "mode: no-cors" even though the transfer is from localhost to localhost.


Solution

  • Sorry, I'm answering my own question. I found a solution and it's one I hadn't seen before in any of the posts related to this problem, perhaps because it's on express verion 4.21.1:

    Simply change the following:

    const express = require('express');
    const app = express();
    const port = 3100;
    
    app.use(express.json());
    

    To this:

    const express = require('express');
    const app = express();
    var cors = require('cors')
    const port = 3100;
    
    app.use(cors())
    
    app.use(express.json());
    

    you must load the cors pakage with

    npm install cors
    

    and see:

    https://github.com/expressjs/cors?tab=readme-ov-file#enabling-cors-pre-flight
    

    for more information.

    With that I could remove the mode: no-cors line from then origin fetch.