从React到Node服务器的ajax调用中的数据未定义。

huangapple go评论70阅读模式
英文:

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

我有一些想法:

  1. 尝试将数据解析为字符串。如果要发送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

  1. 您可能与express的请求体解析器配置有问题。
英文:

I have a few ideas:

  1. 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

  1. You have problem with express body parser configuration.

huangapple
  • 本文由 发表于 2023年1月4日 23:13:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75007496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定