【问题标题】:Response body is null(Fetch request) [duplicate]响应正文为空(获取请求)[重复]
【发布时间】:2020-04-17 08:12:19
【问题描述】:

我正在尝试向银行 API 发出请求,并以 json 格式获取其分支机构。

但我得到一个空洞的回应。 Response

虽然,如果我将链接插入浏览器,我会得到 json 格式。

https://api.privatbank.ua/p24api/pboffice?json&city=Ивано-Франковск

这就是请求的工作方式Results

错误Error

var address = document.getElementById('address').value;

function postData(url = '', data = {}) {
  console.log(url);
  
    return fetch(url, {
        method: 'GET', 
        mode: 'no-cors', 
        headers: {
          "Accept": "application/json",
          'Access-Control-Allow-Origin':'*'
      }
        
    }).then(response => {
      console.log(response);
      if (response.ok)
      {
        response.json()
      }
      else {
        throw new Error('Something went wrong');
      }
    }); 
}

postData(`https://api.privatbank.ua/p24api/pboffice?json&city=${address}`, {})
  .then(data => console.log(JSON.stringify(data))) 
  .catch(error => console.error(error));

`

【问题讨论】:

    标签: javascript api cors fetch


    【解决方案1】:

    您正在将其作为无cors 请求执行。这些受到严格限制,您无法阅读正文。

    请参阅 stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input

    此外,您不会返回 .json() 的结果,因此您的函数在所有情况下都会向 undefined 返回一个承诺。

    【讨论】:

    • response.json () 也无济于事
    • 你是对的 - 那是另一回事 - 但根本原因确实是不正确。
    【解决方案2】:

    我认为您正在尝试使用 no-cors 来获取数据,而该站点未提供正确的标头,那么您的代码将无法访问响应 正确的解释可见how to process fetch response from an 'opaque' type?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 2021-12-26
      • 1970-01-01
      • 2020-04-29
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多