英文:
Data in ajax call from React to Node server is undefined
问题
以下是翻译好的部分:
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打印出"Request received",然后是undefined
。如果我将日志从req.body
更改为req
,它仍然是undefined
。
英文:
I'm trying to just send data from my React frontend to Node backend using jquery's ajax method. The api request is being received by Node, but the data is undefined.
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
. It's still undefined if I log req
instead of req.body
.
答案1
得分: 0
我有一些想法:
- 尝试将数据解析为字符串。如果要发送HTTP请求,数据应该格式化为正确的类型,例如文本(字符串)或JSON。
当数据是一个对象时,除非将processData选项设置为false,否则jQuery会从对象的键/值对生成数据字符串。
来源:https://api.jquery.com/jQuery.ajax/
实际上,您的数据看起来是这样的:
data: '{"name":"John","place":"Alaska"}'
这就是为什么express可能在解析方面会出现问题。
参考:https://stackoverflow.com/questions/4159701/jquery-posting-valid-json-in-request-body
- 您可能与express的请求体解析器配置有问题。
英文:
I have a few ideas:
- Try to parse the data to a string. If you want to send an HTTP request it should be formatted to the proper type eg. text (string) or JSON.
> 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/
Your data actually looks like that:
> data: '{"name":"John","place":"Alaska"}'
Thats why express may some problems with parsing.
Reference: https://stackoverflow.com/questions/4159701/jquery-posting-valid-json-in-request-body
- You have problem with express body parser configuration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论