[英]req.body is undefined using express
I'm trying to fetch POST data to my node.js server which is running express. 我正在尝试将POST数据获取到运行express的node.js服务器。 I did configure the bodyparser BEFORE the routes :
我确实在路由之前配置了bodyparser:
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. 实际上,
console.log(req.body)
总是给我一个未定义的值。
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. 我真的不知道我的问题可能来自哪里,我没有问题使用Postman和
JSON.stringify(this.state)
发布数据JSON.stringify(this.state)
返回一个漂亮且正确的JSON字符串。 I then suppose that the problem come from my API but I don't have a clue how to fix it. 然后,我认为问题出在我的API上,但是我不知道如何解决它。 Maybe no-cors mode is corrupting my request ?
也许no-cors模式损坏了我的请求? 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. 更新:我发现我的客户端没有发送“ Content-Type”标头,即使我在获取请求中进行了设置。 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)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.