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

如何在JavaScript中判断HTTP响应是否为纯文本?

解决方案

你可以通过解析响应的Content-Type头,用通用规则判断是否为可安全转为文本的资源,不用逐一维护具体类型:

fetch("http://example.org/" + path)
  .then(response => {
    const contentType = response.headers.get('Content-Type');
    if (!contentType) {
      // 无Content-Type头时默认按非文本处理,可根据需求调整
      return response;
    }
    // 提取基础类型,忽略charset等附加参数
    const baseType = contentType.split(';')[0].trim();
    // 判断是否为文本类资源
    const isTextType = baseType.startsWith('text/') ||
      ['application/javascript', 'application/json', 'application/xml', 'application/xhtml+xml'].includes(baseType) ||
      contentType.includes('charset=');

    if (isTextType) {
      return response.text().then(text => {
        // 执行你的replace操作
        return text.replace(/目标内容/g, '替换内容');
      });
    } else {
      // 非文本资源直接返回原响应
      return response;
    }
  })
  .then(processedResult => {
    // 处理最终结果
    console.log(processedResult);
  })
  .catch(err => console.error('请求失败:', err));

逻辑说明

浏览器能识别非文本资源,核心也是靠Content-Type头判断,没有额外的"魔法检测"。我们的规则覆盖了绝大多数场景:

  • 所有text/开头的类型都是标准文本资源;
  • 加入常见的文本类application类型(比如JS、JSON);
  • 带charset参数的响应基本都是文本(二进制资源不会指定字符编码)。

这种方式不用逐一新增类型,只要服务器返回正确的Content-Type,新的文本类型也能自动适配。如果服务器返回的Content-Type不准确,那不管是浏览器警告还是我们的判断都会失效,这种情况需要后端修正配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:32:42