Failed to execute 'fetch' on 'Window': Failed to read the 'headers' property fro...
错误信息
Failed to execute 'fetch' on 'Window': Failed to read the 'headers' property from 'RequestInit': String contains non ISO-8859-1 code point.
AI 解决方案
报错分析报告
1.错误翻译
原文:Failed to execute 'fetch' on 'Window': Failed to read the 'headers' property from 'RequestInit': String contains non ISO-8859-1 code point.
译文:在“Window”上执行“fetch”失败:无法从“RequestInit”读取“headers”属性:字符串包含非ISO-8859-1编码的代码点。
2.原因分析
fetch请求的headers配置中包含非ISO-8859-1编码的字符(如中文、 emoji 等),违反API对头值的编码要求。 fetch的RequestInit.headers时,字符串值含非法编码字符。3.解决方案
// 修复方案1:编码非ISO字符(以中文为例)
const encodeHeaderValue = (str) => btoa(unescape(encodeURIComponent(str))); // UTF-8→Base64
const headers = {
"Content-Type": "application/json",
"X-User-Name": encodeHeaderValue("李四") // 编码后的值
};
// 修复方案2:使用Headers对象(更规范的写法)
const headerObj = new Headers();
headerObj.append("Content-Type", "application/json");
headerObj.append("X-User-Name", encodeHeaderValue("李四"));
// 调用fetch
fetch("/api/data", {
method: "GET",
headers: headerObj // 或 headers(方案1的对象)
});
4. 预防措施
Headers对象构造请求头,而非普通对象,减少编码错误。 eslint-plugin-fetch检查编码问题。