两种JavaScript GET请求失败排查:调用API是否遗漏步骤?
问题分析与解决
你的代码存在几个关键问题,导致请求结果无法正常显示,逐一拆解:
1. 跨域限制(核心原因)
Postman不受浏览器同源策略约束,但浏览器中运行的JS脚本只能请求和当前页面域名、协议、端口完全一致的资源。如果http://example.com/movies.json和你当前页面的域名不同,浏览器会拦截响应,你可以打开F12开发者工具的「Console」面板,应该能看到CORS相关的错误提示。
2. document.write的致命问题
- 异步请求(fetch/XHR)完成后调用
document.write,会直接清空当前页面的所有内容,因为此时页面已经加载完成,document.write会开启新的文档流覆盖原有内容。 - 直接写入JSON对象(比如
document.write(json)),页面只会显示[object Object],需要用JSON.stringify()把对象转成字符串。
3. XHR代码的顺序错误
xhr.responseType = "json"必须在xhr.send()之前设置,否则无法正确解析JSON响应。onload事件监听应该在send()之前绑定,避免请求提前完成导致事件回调没触发。
4. 缺少错误处理逻辑
- Fetch默认不会对HTTP错误状态码(如404、500)抛出异常,必须手动检查
response.ok。 - 两种请求都没处理网络错误(如连接失败、超时)。
修正后的代码示例
建议用console.log代替document.write做调试,避免页面被覆盖,同时能看到完整的响应内容:
Fetch 写法
<html> <script type="text/javascript"> // Fetch 请求 fetch("http://example.com/movies.json") .then((response) => { // 检查HTTP状态是否正常 if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then((json) => { console.log("Fetch响应结果:", json); // 如果要显示在页面,用DOM操作而非document.write document.body.innerHTML += "<pre>" + JSON.stringify(json, null, 2) + "</pre>"; }) .catch((error) => { console.error("Fetch请求失败:", error); document.body.innerHTML += "<p>请求失败: " + error.message + "</p>"; }); document.write("Debug - after the first fetch <br><br>"); </script> </html>
XHR 写法
<html> <script type="text/javascript"> // XHR 请求 const xhr = new XMLHttpRequest(); // 先绑定事件监听 xhr.onload = () => { if (xhr.readyState == 4) { if (xhr.status == 200) { console.log("XHR响应结果:", xhr.response); document.body.innerHTML += "<pre>" + JSON.stringify(xhr.response, null, 2) + "</pre>"; } else { console.error("XHR请求错误:", xhr.status); document.body.innerHTML += `<p>Error: ${xhr.status}</p>`; } } }; // 处理网络错误 xhr.onerror = () => { console.error("XHR网络请求失败"); document.body.innerHTML += "<p>网络请求失败</p>"; }; // 设置响应类型 xhr.responseType = "json"; // 打开请求并发送 xhr.open("GET", "http://example.com/movies.json"); xhr.send(); document.write("XMLHTTP Request has been created and sent <br><br> after the XMLHTTPRequest"); </script> </html>
调试建议
- 打开F12开发者工具,查看「Console」面板的错误信息,确认是否存在CORS或其他请求错误。
- 查看「Network」面板,检查请求的状态码、响应头和响应内容,确认请求是否真正到达服务器并返回了正确结果。
内容的提问来源于stack exchange,提问作者Jon Billingsley
相关产品推荐
相关产品推荐

