使用Cloudflare Worker返回JSON时JSON.parse异常但数据可正常获取
问题分析与解决方法
问题原因
你的代码里onreadystatechange事件会在请求的所有阶段触发(XMLHttpRequest的readyState有0-4共5个状态),并非只有请求完成的时候。当readyState为2、3时,响应内容还未完全返回,Http.response是空字符串或不完整的JSON片段,这时候执行JSON.parse(Http.response)就会抛出Unexpected end of JSON input错误。而最后一次触发事件时,readyState变为4(请求完成),响应内容完整,所以能正确解析并拿到parsed.pswd的值——这就是代码能运行但控制台一直报错的核心原因。
解决方案
修改前端的请求处理逻辑,仅当请求完成(readyState === 4)且响应成功(status === 200)时,再解析JSON:
const Http = new XMLHttpRequest(); const url = my_url; Http.open("GET", url); Http.send(); Http.onreadystatechange = (e) => { // 只在请求完成且成功时处理响应 if (Http.readyState === 4 && Http.status === 200) { console.log(Http.response); var parsed = JSON.parse(Http.response); document.getElementById("json_response_code").textContent = parsed.pswd; } };
额外优化建议
- 可以添加错误处理逻辑,覆盖请求失败的场景:
Http.onreadystatechange = (e) => { if (Http.readyState === 4) { if (Http.status === 200) { console.log(Http.response); var parsed = JSON.parse(Http.response); document.getElementById("json_response_code").textContent = parsed.pswd; } else { console.error(`请求失败,状态码:${Http.status}`); // 此处可添加前端错误提示逻辑 } } };
- 也可以改用更现代的
fetch API替代XMLHttpRequest,写法更简洁且原生支持Promise:
fetch(my_url) .then(response => { if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.json(); }) .then(data => { document.getElementById("json_response_code").textContent = data.pswd; }) .catch(error => { console.error(error); });
内容的提问来源于stack exchange,提问作者NicoCaldo
相关产品推荐
相关产品推荐

