如何解决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
相关产品推荐
相关产品推荐

