Failed to execute 'fetch' on 'Window': Failed to read the 'headers' property fro...

2026年04月29日 01:11 processing

错误信息

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对头值的编码要求。

  • 发生位置:设置fetchRequestInit.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. 预防措施


  • 最佳实践1:避免在HTTP头值中直接使用非ISO-8859-1字符,需传递非ASCII内容时用Base64/URL编码。

  • 最佳实践2:优先用Headers对象构造请求头,而非普通对象,减少编码错误。

  • 推荐工具:用[Postman](https://www.postman.com/)预校验头值合法性,或用ESLint插件eslint-plugin-fetch检查编码问题。