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

如何在HTML中打印JSON?请求排查打印时显示undefined的问题

问题排查:页面显示undefined的原因及修复方案

核心问题

你的代码中,第二个.then()回调里的console.log()返回值是undefined,Promise链式调用会把前一个回调的返回值传给下一个回调,所以第三个.then()拿到的out就是undefined,最终导致页面显示undefined。

修复方案

有两种可行的修复方式:

方式一:合并回调逻辑

把日志打印和页面渲染放在同一个.then()里,直接使用正确的out数据:

let url = 'https://ac7minh6n7s3rw4qfchrofbwai0amiko.lambda-url.eu-north-1.on.aws/';

fetch(url)
.then(res => res.json())
.then(out => {
  console.log('JSON: ', out);
  document.write('JSON string: ', JSON.stringify(out));
})
.catch(err => { throw err })

方式二:显式返回数据

如果需要分开链式调用,必须在第二个.then()里把out返回出去,供后续回调使用:

let url = 'https://ac7minh6n7s3rw4qfchrofbwai0amiko.lambda-url.eu-north-1.on.aws/';

fetch(url)
.then(res => res.json())
.then(out => {
  console.log('JSON: ', out);
  return out; // 显式返回数据,传递给下一个then
})
.then(out => document.write('JSON string: ', JSON.stringify(out)))
.catch(err => { throw err })

额外建议

document.write()在页面加载完成后调用会覆盖整个页面,更推荐使用DOM元素来展示内容,比如先在HTML中添加一个容器:

<div id="result-container"></div>

然后修改JavaScript代码:

.then(out => {
  console.log('JSON: ', out);
  document.getElementById('result-container').textContent = 'JSON string: ' + JSON.stringify(out);
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:15:22