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

React中如何转换POST请求后端响应的文本?

问题描述

后端通过Swagger返回的响应内容正常,但在浏览器网络面板中查看时显示异常,Postman中使用response.text()可得到正常结果。尝试了解码、编码、转换为Base64等方法,均无法在React中用JavaScript实现与Swagger、Postman一致的结果,求解决方法。

相关截图

  • Swagger正常响应:Swagger正常响应
  • 浏览器网络面板异常响应:浏览器网络面板异常响应
  • Postman使用response.text()得到正常结果:Postman正常结果

解决方案

这种情况核心原因通常是后端响应编码与浏览器默认解析编码不匹配,或响应头未正确声明字符编码,可按以下步骤解决:

1. 强制指定编码读取响应

如果后端返回的是GBK/GB2312等非UTF-8编码,浏览器默认用UTF-8解析会出现乱码。可借助TextDecoder手动指定编码读取:

async function fetchTargetData() {
  try {
    const response = await fetch('/your-api-path');
    // 根据实际编码调整,比如'gbk'、'gb2312'
    const decoder = new TextDecoder('gbk');
    const arrayBuffer = await response.arrayBuffer();
    const normalText = decoder.decode(arrayBuffer);
    console.log(normalText);
  } catch (err) {
    console.error('请求失败:', err);
  }
}

2. 优先尝试直接用response.text()读取

Postman中response.text()能正常解析,说明直接读取文本可能绕过编码猜测问题。试试跳过json()方法,直接读取后按需转换:

async function fetchTargetData() {
  const response = await fetch('/your-api-path');
  const text = await response.text();
  // 如果是JSON格式,手动转换为对象
  try {
    const data = JSON.parse(text);
    console.log(data);
  } catch (e) {
    console.log('非JSON格式内容:', text);
  }
}

3. 检查并修正响应头Content-Type

确认后端返回的Content-Type头是否包含正确的字符集声明,比如:

Content-Type: application/json; charset=gbk
或 Content-Type: text/plain; charset=utf-8

如果后端未添加charset字段,浏览器会自行猜测编码,容易出错。联系后端补充该声明是从根源解决问题的方法。

4. 排查压缩导致的异常

如果后端启用了Gzip/Brotli压缩,个别情况下浏览器自动解压会失败,可尝试用pako库手动解压:

import pako from 'pako';

async function fetchTargetData() {
  const response = await fetch('/your-api-path');
  const arrayBuffer = await response.arrayBuffer();
  const decompressedText = pako.inflate(arrayBuffer, { to: 'string' });
  console.log(decompressedText);
}

内容的提问来源于stack exchange,提问作者Borna Pavlić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:55:31