为什么发送 fetch() 时我的响应数据未定义?

Joh*_*mon 1 javascript fetch node.js

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

服务器很好地收到了发布请求,并且我能够记录 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))
Run Code Online (Sandbox Code Playgroud)

服务器代码

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

Chrome 能够读取响应,但数据字段显示未定义

Que*_*tin 7

then方法需要回调。该回调返回一个值。

\n

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

\n

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

\n

这是你的功能:

\n
\n

res => console.log(res)

\n
\n

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

\n

console.log 总是返回undefined

\n

所以接下来的 then 函数:

\n
\n
data => console.log(data)\n
Run Code Online (Sandbox Code Playgroud)\n
\n

\xe2\x80\xa6 被undefined传递到data.

\n
\n

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

\n

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

\n
    \n
  1. 将数据从体内取出
  2. \n
  3. 从函数中返回它
  4. \n
\n

例如:

\n
.then(res => {\n    console.log(res);\n    return res.json();\n})\n.then(data => console.log(data))\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n