[英]Data in ajax call from React to Node server is undefined
I'm trying to just send data from my React frontend to Node backend using jquery's ajax method.我正在尝试使用 jquery 的 ajax 方法将数据从我的 React 前端发送到 Node 后端。 The api request is being received by Node, but the data is undefined. Node 正在接收 api 请求,但数据未定义。
React:反应:
console.log("Making Node API call");
$.ajax({
method: "POST",
url: "test",
data: {
name: "John",
place: "Alaska"
}
}).done(function( msg ) {
console.log(msg);
});
Node:节点:
app.post("/test", (req, res) => {
console.log("Request received");
console.log(req.body);
});
Node prints "Request received", followed by undefined
. Node 打印“Request received”,然后是undefined
。 It's still undefined if I log req
instead of req.body
.如果我记录req
而不是req.body
,它仍然是未定义的。
I have a few ideas:我有几个想法:
When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false source: https://api.jquery.com/jQuery.ajax/当数据是 object 时,jQuery 从对象的键/值对生成数据字符串,除非 processData 选项设置为 false 来源: https://api.jquery.com/jQuery.ajax/
Your data actually looks like that:您的数据实际上是这样的:
data: '{"name":"John","place":"Alaska"}'数据:'{“名称”:“约翰”,“地点”:“阿拉斯加”}'
Thats why express may some problems with parsing.这就是为什么 express 可能会在解析时出现一些问题。
Reference: jQuery posting valid json in request body参考: jQuery 在请求正文中发布有效 json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.