【问题标题】:Sending parameters from React JS to Node JS servers returns as undefined从 React JS 向 Node JS 服务器发送参数返回未定义
【发布时间】:2021-05-24 23:06:58
【问题描述】:

我通过以下方式将uid 发送到我的节点 JS 服务器:

  fetch(encodeURI("http://localhost:9000/notify", {
        body: JSON.stringify({uid:uid})
      }))
      .then(res => alert(res))
      alert(uid)

uid 是一串数字) 但是,当尝试在 API 中读取 uid 时,控制台返回 undefined for body

app.get("/notify", async (req, res) => {
  console.log('req.body returns as undefined')
  console.log(req.body.uid)

我该如何解决这个问题?

【问题讨论】:

  • 这看起来像快递;你启用body parser了吗?您可能还必须在获取请求中添加Content-Type: application/json 标头。 (还要注意 React 在这里完全不相关)

标签: javascript node.js reactjs


【解决方案1】:

fetch 不会在 GET 请求中发送正文。

在客户端上,您需要:

  • 指定method为POST(GET为默认)
  • 指定内容类型请求头
  • 将选项对象作为第二个参数传递给fetch,而不是作为第二个参数传递给encodeURI(就此而言,根本不要使用encodeURI,这里不需要它)。李>

请参阅MDN: Using fetch 了解示例

在您需要的服务器上:

【讨论】:

    猜你喜欢
    • 2019-07-20
    • 2013-03-31
    • 2018-09-28
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 2020-06-30
    相关资源
    最近更新 更多