【问题标题】:UnhandledPromiseRejectionWarning: FetchError: invalid json response body atUnhandledPromiseRejectionWarning: FetchError: invalid json response body at
【发布时间】:2020-03-06 07:11:55
【问题描述】:

我得到错误:

UnhandledPromiseRejectionWarning: FetchError: invalid json response body at {url}
reason: Unexpected token < in JSON at position 0

我的代码:

const fetch = require('node-fetch');

const url = 'Reeeealy long url here';

fetch(url)
  .then(res => res.json())
  .then(console.log);

如果 url 长于 ~8k+ 个字符 api 返回

400 Bad Request
Request Header Or Cookie Too Large
nginx

显然我不控制那个 api。

我能做些什么来防止这种情况发生?

网址结构:

1) 域

2) api版本

3) 端点

4) 请求资料(最长的部分)

5) id 结尾

看起来像这样:https://example.com/v1/endpoint/query?query=long_part_here&amp;ids=2145132,532532,535

【问题讨论】:

    标签: javascript node.js fetch node-fetch


    【解决方案1】:

    如果预期“long_part”很长,这听起来像是一个设计不佳的 api。它应该使用POST 而不是GET 请求,以便可以在body 对象中发送长数据集。您能否查看 API 是否允许端点的 POST 版本允许这样做?

    如果没有可用的POST,并且您不控制 API,那么您没有太多选择。我能想到的唯一一件事是,如果可行的话,您将请求分成多个单独的端点调用(可能每个 id 一个),并且会导致每个请求的 url 大小更短。

    多次调用

    如果您能够执行多个较小的请求,代码可能如下所示:

    const urls = ["firstUrl","secondUrl","nthUrl"];
    let combined = {};
    for (const url of urls) {
      fetch(url)
        .then(res => res.json())
        .then(json => combined = {...combined, ...json};
    }
    console.log(combined);
    

    这假设将结果全部合并到一个对象中是合理的。如果它们应该保持不同,您可以像这样更改最后一个 then

    .then(json => combined = {...combined, {`url${count}`: json}};
    

    count 是一个整数,每次递增,combined 看起来像

    {url1: {/*json from url1*/}, url2: {/*json from url2*/}, ...}
    

    错误处理

    为了更优雅地处理错误,您应该在假设返回 JSON 之前检查结果。因为返回的数据不是JSON,所以您收到JSON 解析错误。当它以&lt; 开头时,它是HTML 所以失败了。你可以这样做:

    fetch(url)
      .then(res => {
        if (res.resultCode == "200") return res.json();
        return Promise.reject(`Bad call: ${res.resultCode}`);
      })
      .then(console.log);
    

    【讨论】:

    • 会检查我是否可以做POST 请求。最有趣的部分是这个 api 由大公司制作,但我不得不处理更糟糕的 api。您对如何将请求拆分为 2n 请求并将其组合成 1 个 json 有什么建议吗?
    • 我进行了编辑以展示您如何进行多个较小的调用
    • 哦,我的意思是更多如何将原始 url 拆分为 n url,如果我知道它不能超过 ~8k 个字符。
    • 回答我必须知道有关端点的详细信息。我看到你在网址的末尾有多个 id。如果每个网址只有一个id 并且数据仅限于该id 的数据,会不会更短?
    • 没有查询总是一样的,但有时你想用相同的查询获得结果,但对于多个 ids
    猜你喜欢
    • 1970-01-01
    • 2020-11-07
    • 2021-10-31
    • 2021-10-01
    • 1970-01-01
    • 2021-12-14
    • 2019-03-26
    • 2021-02-02
    • 1970-01-01
    相关资源
    最近更新 更多