我正在尝试将数据从基于 React.js 的客户端输入发送到用 Node.js 编写的服务器,然后将其放入数据库。我没有错误,提交后,新记录显示在数据库中,但它们是空的。我有两个输入,我将它们加入一个字符串并尝试将其发送到 DB(因此 DB 具有一个属性)。你能检查我的代码,看看有什么问题吗?也许有标题的东西......
这是 React 组件中的函数:
addCompetitor = event => {
event.preventDefault();
const name = this.state.draftCompetitorName;
const lastname = this.state.draftCompetitorLastname;
fetch(`http://localhost:5000/competitors`, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: `${name}${lastname}` })
})
.then(response => response.json())
};
这是服务器 POST 响应:
app.post("/competitors/", urlencodedParser, function (req, res) {
const newCompetitor = new Competitor({ name: req.body.name });
newCompetitor.save().then(competitor => res.json(competitor));
});
这是应用程序配置:
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type",
"X-Requested-With"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
如果没有先安装bodyparser。这会在您的处理程序之前解析中间件中的传入请求正文,这将在req.body
属性下可用。
app.use(bodyParser.json({
limit: '50mb',
parameterLimit: 100000
}))
或者,您使用的快速版本是什么?是否大于 4.16?然后你也可以使用
app.use(express.json());
请参阅此处的注释
https://expressjs.com/en/api.html#express.json
修改你的代码
let databody = {
"name": `${name}${lastname}`,
"otherprop": this.state.otherprop
}
从前端使用 body: JSON.stringify(databody),
在 express 端 remove urlencodedParser
,应该如下所示:
app.post("/competitors", function (req, res) {
console.log(req.body);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句