【问题标题】:Fetch() Response.text() is undefinedFetch() Response.text() 未定义
【发布时间】:2020-06-30 13:59:24
【问题描述】:

首先很抱歉,如果以前有人问过这个问题,我尝试了其他类似的问题,但答案对我没有帮助。

我正在使用 fetch() 获取 UTF-8 编码文件,但我的 response.text() 不断返回 undefined。我在 Postman 中测试过,它返回的编码数据没有问题。

示例代码:

async function testCode() {
  const response = await fetch(url1);
  const data = await response.text();
  console.log(response);
  console.log(data);
  return data;
}

Console.log(数据):

{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "219BA1C8-5BF8-41E3-97C9-BA0A7684D712", "name": "mgaonline.ubx", "offset": 0, "size": 9416, "type": "application/ubx"}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "219BA1C8-5BF8-41E3-97C9-BA0A7684D712", "name": "mgaonline.ubx", "offset": 0, "size": 9416, "type": "application/ubx"}}, "bodyUsed": true, "headers": {"map": {"cache-control": "private", "content-disposition": "attachment; filename=mgaonline.ubx", "content-length": "9416", "content-type": "application/ubx", "date": "Tue, 30 Jun 2020 14:17:13 GMT", "server": "Microsoft-IIS/10.0", "x-aspnet-version": "4.0.30319", "x-powered-by": "ASP.NET"}}, "ok": true, "status": 200, "statusText": undefined, "type": "default", "url": "https://online-live1.services.u-blox.com/GetOnlineData.ashx?token=Janf2Rk0CkKHlMi2hWUOjg;gnss=gps,glo,gal,qzss;datatype=eph,alm,aux;"}

当我尝试访问 [Object] 时,它会显示为 undefined 但在 Postman 中,它返回正确的 utf-8 编码的 8 位二进制数据。

【问题讨论】:

  • 看看这里javascript.info/fetch
  • @HarmandeepSinghKalsi 这不是 json,这是他们自己的 ubx 类型,但我会尝试使用它
  • 你能显示“console.log(data)”吗?愚蠢的问题,但你确定这是你需要的 GET 请求吗?
  • @Arcord 将在问题中作为编辑发布,因为它与评论相比太长了
  • 当然 :-) 当你尝试“.blob()”或“.arrayBuffer()”时,你得到了什么吗?如果是,我猜这与您在响应中获得的接受标头的内容有关...由于浏览器不知道它(不认为这是标准的),也许他拒绝将内容作为文本提供给您?

标签: javascript react-native fetch


【解决方案1】:

我了解到 React-Native 在默认情况下不支持编码的二进制数据,因此必须使用 rn-fetch-blob ,它可以立即正常工作。浪费了 2 天时间。

【讨论】:

    【解决方案2】:

    尝试在标题中设置内容类型,可能会起作用

    fetch(url1, { Content-Type: text/html; charset=utf-8} );

    【讨论】:

    • 返回的标头中列出的内容类型是“application/ubx”,所以我尝试了以下标头: const myHeaders = new Headers({ "Content-Type": "application/ubx", Accept: “应用程序/ubx”,字符集:“utf-8”});
    • “内容类型”标头在 GET 请求中没有真正意义(因此没有正文):developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type ...您的意思是“接受”标头吗?
    【解决方案3】:

    试试这个代码

      const utf8Decoder = new TextDecoder('utf-8');
      const response = await fetch(fileURL);
      const reader = response.body.getReader();
      let { value: chunk, done: readerDone } = await reader.read();
      chunk = chunk ? utf8Decoder.decode(chunk) : '' ; 
    

    来自fetch API

    【讨论】:

    • 我不能,因为数据本身不是 JSON 可解析的:SyntaxError: JSON Parse error: Unexpected identifier "undefined"
    • 我已经编辑了我的答案,你可以试试吗console.log(chunk)
    • 我试过了,但得到这个错误:TypeError: undefined is not an object (evaluating 'response.body.getReader')response 上似乎没有属性body
    猜你喜欢
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多