【问题标题】:Why is my response data undefined when sending a fetch()?为什么发送 fetch() 时我的响应数据未定义?
【发布时间】:2021-03-17 14:32:49
【问题描述】:

我正在尝试在客户端使用 fetch() 将数据发送到我的 nodeJS 服务器或从我的 nodeJS 服务器发送数据。

服务器接收到 post 请求很好,我可以记录 req 变量,但是当我 res.send('any data') 时,客户端无法检测到数据。奇怪的是chrome可以看到响应但我根本不知道如何引用数据!

客户代码

fetch('/',{
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
  user:{
    name: 'John',
    email: 'J@B.com',
  }
})
.then(res => console.log(res))
.then(data => console.log(data))
.catch((error) => console.error('Error:',error))

服务器代码

app.post('/', (req,res) => {
  console.log(req.body.user)
  res.send('hello?')
})

Chrome able to read response but data field showing undefined

【问题讨论】:

    标签: javascript node.js fetch


    【解决方案1】:

    then 方法接受回调。该回调返回一个值。

    如果该值是一个承诺,那么它将被采用,当它被解析时,next then 函数将接收该承诺的解析值。

    如果该值不是承诺,则下一个 then 函数将接收该值。

    这是你的功能:

    res => console.log(res)

    返回console.log(res)的返回值。

    console.log 总是返回undefined

    所以接下来的 then 函数:

    data => console.log(data)
    

    …将undefined 传递给data


    你需要返回你真正关心的值。

    如果该值是响应正文中的数据,那么您需要:

    1. 从正文中取出数据
    2. 从函数中返回

    例如:

    .then(res => {
        console.log(res);
        return res.json();
    })
    .then(data => console.log(data))
    

    这假设您从正文中获取 JSON。其他类型的数据还有其他方法。

    【讨论】:

    • 其实是文字
    • 然后使用response.text()
    • 非常感谢,这解释了我的问题!我现在已经解决了这个问题,我认为我需要对 Promise 进行更多研究(我最近才开始使用 Javascript)谢谢。
    【解决方案2】:

    因为这不是您使用 fetch 的方式,而您的第一个履行处理程序正在返回调用 console.log 的结果,它始终是 undefined

    在您的第一个履行处理程序中,您需要阅读响应的正文(如果res.ok 为真)。例如,要将其读取为文本,您可以在响应中调用 text 方法:

    fetch("/",{
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
        user:{
            name: "John",
            email: "J@B.com",
        }
    })
    .then(res => {
        if (!res.ok) {
            throw new Error(`HTTP error ${res.status}`);
        }
        return res.text();
    })
    .then(text => console.log(text))
    .catch((error) => console.error("Error:",error));
    

    Response object 上除了text 之外还有其他方法:jsonarrayBufferblobformData。您使用哪一个取决于您要发回的内容以及您想用它做什么。

    注意res.ok 上的检查。这(恕我直言)在fetch API 中有点像枪,它只拒绝对 network 错误的承诺,而不是 HTTP 错误。所以你必须自己检查那些。 (我在this blog post中有更多描述。)

    【讨论】:

      【解决方案3】:

      res 变量的类型为 Response,因此您需要像这样以文本形式检索正文:

      fetch('/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          user: {
            name: 'John',
            email: 'J@B.com',
          }
        })
      })
      .then(res => res.text())
      .then(res => console.log(res))
      .catch((error) => console.error('Error:', error))
      

      【讨论】:

        【解决方案4】:
        then(res => res.json()) // then(res => res.text())  for converting to text
          .then(data => console.log(data));
        .catch((error) => console.error('Error:',error))
        

        查看使用fetch

        【讨论】:

        • OP 的响应不是 JSON。
        猜你喜欢
        • 1970-01-01
        • 2012-06-23
        • 1970-01-01
        • 2020-01-27
        • 1970-01-01
        • 1970-01-01
        • 2021-07-20
        • 2022-09-23
        • 2019-10-27
        相关资源
        最近更新 更多