You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决JS中从fetch的res.body ReadableStream提取数据返回undefined问题

问题原因与解决方案

你的问题出在前端fetch的回调逻辑里:第一个.then中调用了res.json(),但没有返回这个Promise对象,导致第二个.then接收到的是默认的undefined。

修复后的前端代码

fetch('/playground',{
  method: 'POST',
}).then(function(res){
  // 必须返回res.json()的Promise,才能把数据传递给下一个then
  return res.json()
}).then(data => console.log(data))

也可以用更简洁的箭头函数写法(箭头函数会自动返回表达式结果):

fetch('/playground',{ method: 'POST' })
  .then(res => res.json())
  .then(data => console.log(data))

后端代码验证

你的Node.js后端代码没有问题,res.send({message: "Hello from backend"})会自动将对象序列化为JSON,并设置正确的Content-Type: application/json响应头,前端修复后就能正常接收预期的{message: "Hello from backend"}对象。

内容的提问来源于stack exchange,提问作者Abhay Sahu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:23:14