简体   繁体   中英

Empty body POST request express

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))
   }

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,    
        })
    })

The problem is you aren't ever telling the server itself to listen for incoming connections on port 5000 .

Try adding this to the bottom of your node app:

app.listen(5000, function() {
    console.log("Listening on port 5000");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM