我正在尝试在客户端使用 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: '[email protected] /cdn-cgi/l/email-protection',
}
})
.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 能够读取响应,但数据字段显示未定义 https://i.stack.imgur.com/FKPoH.png
The then
方法需要回调。该回调返回一个值。
如果该值是一个承诺,那么它将被采用,并且当它得到解决时,然后next then
函数将收到该承诺的解析值。
如果该值不是承诺,则下一个then
函数将收到该值。
这是你的功能:
res => console.log(res)
它返回的返回值是console.log(res)
.
console.log
always回报undefined
所以接下来的 then 函数:
data => console.log(data)
… gets undefined
传递到data
.
您需要返回您真正关心的值。
如果该值是响应正文中的数据,那么您需要:
- 将数据从体内取出
- 从函数中返回它
例如:
.then(res => {
console.log(res);
return res.json();
})
.then(data => console.log(data))
这假设您从正文中获取 JSON。对于其他类型的数据还有其他方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)