简体   繁体   中英

req.body is undefined using express

I'm trying to fetch POST data to my node.js server which is running express. I did configure the bodyparser BEFORE the routes :

const
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
twig = require('twig'),
server = app.listen(8000,"localhost",()=>{
    let host = server.address().address
    let port = server.address().port
    console.log("Running at http://" + host+ ":"+port)
})

app.use(bodyParser.json());
const routes = require('./src/route')(app)

Here is my controller method :

create: (req,res,next) => {
    console.log(req.body.title)
    return db.dev.create({
        title : req.body.title,
        description: req.body.description,
        reportedBy: req.body.reportedBy,
        sprintId: req.body.sprintId,
        estimated : req.body.estimated
    })
        .then((dev)=>res.json(dev))
        .catch((err)=>next(err))
}

In fact, console.log(req.body) is always giving me an undefined value.

And here is the fetch request sent from my client :

create(){
    return fetch("http://localhost:8000/devs",
        {
            method:"POST",
            mode:"no-cors",
            headers:{
                "Content-Type":"application/json",
                "Accept":"application/json",
                "Access-Control-Allow-Origin":"*"
            },
            body : JSON.stringify(this.state)
        }).then(()=>console.log(JSON.stringify(this.state))
}

I don't really know where my issue might come from, I have no problem posting data using Postman and JSON.stringify(this.state) returns a pretty and correct JSON string. I then suppose that the problem come from my API but I don't have a clue how to fix it. Maybe no-cors mode is corrupting my request ? If I don't set it I have a "cannot fetch error".

I hope some of you will help me as I already lost some hair trying to figure this out.

Thank you a lot for your time.

UPDATE : I found out my client isn't sending "Content-Type" headers even if I set it up in my fetch request. Working on it

Could you try to reorder your server such that it looks like this

const
    express = require('express'),
    bodyParser = require('body-parser'),
    app = express(),
    twig = require('twig'),

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

const routes = require('./src/route')(app)

server = app.listen(8000,"localhost",()=>{
    let host = server.address().address
    let port = server.address().port
    console.log("Running at http://" + host+ ":"+port)
})

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