Home > Software design >  Empty body POST request express
Empty body POST request express

Time:01-04

I trying to setup an express server, however all of my POST request have an empty body once it reach the server. I've tried to use body-parser or express.json() but the result didn't change. A console.log(req.body) only give me a empty object {}

The data is sent without problems, as the devs tools networks shows the json object that I'm trying to send. The code is still fairly simple in both the express api and the react website so I'm not sure what I'm doing wrong here:

Express api :

const bodyParser = require('body-parser');
var express = require('express');
var router = express.Router();
var app = express();

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

router.use((req,res,next)=>{
    res.header('Access-Control-Allow-Origin','*')
    res.header("Access-Control-Allow-Methods", "GET, POST");
    next()
})

router.post("/",function (req,res,next){
    console.log(req.body)
    res.send("blabla")
})

module.exports = router;

React :

async createChat(){
        var data = {
            method:'POST',
            body:JSON.stringify()
        }
        console.log(data)
        await fetch('http://localhost:5000/create_chat',{
            method: 'POST',
            body: JSON.stringify({
                chat_name:this.state.chatName,
                password : {
                    enabled: this.state.passwordYesNo,
                    password : this.state.password
                },
                public:this.state.publicYesNo,    
            })
        })
        .then((res)=>res.text())
        .then((res)=>console.log(res))
   }

CodePudding user response:

The issue is caused by the missing headers parameter in the fetch call. You can update the fetch call like this and try.

    await fetch('http://localhost:5000/create_chat',{
        method: 'POST',
        headers: new Headers({'content-type': 'application/json'}),
        body: JSON.stringify({
            chat_name:this.state.chatName,
            password : {
                enabled: this.state.passwordYesNo,
                password : this.state.password
            },
            public:this.state.publicYesNo,    
        })
    })
  • Related