首页 > 解决方案 > 如何在不告诉 fetch “mode: “no-cors” 的情况下避免 CORS 错误?

问题描述

我最初的问题(JavaScript fetch API data and use XML response as an object)被标记为SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data using fetch的副本,所以我问另一个问题,建立在我所学(或假设)的基础之上:

如果我没有定义“{ mode:”no-cors“}”,则在 JS 中使用 fetch() 调用 API 时出现 cors 错误。当我运行本地服务器时,我也会收到错误消息!当我定义 no-cors 时,我没有收到 cors 错误,但响应似乎是空的。

如何避免 cors 错误并获得响应?

我的代码如下:

async function apiCall() {
  const url =
    "https://service.runmyaccounts.com/api/latest/clients/apitest/invoices?api_key=d1bvbxkI8f1bnMBJ4sZiC-xupl4fOEzf"; // yes this is ok to publish as it is in the api documentation and just a test account
  try {
    const response = await fetch(url, {
      headers: {
        "Content-Type": "text/xml"
      }
    });
    const data = await response.text();
    console.log(data);
    //return data;
  } catch (err) {
    console.log(err);
  }
}
apiCall();

标签: javascriptcorsfetchresponse

解决方案


它似乎被了但是......工作:使用fetch代理

var proxy_url = 'https://cors-anywhere.herokuapp.com/';
var main_url = 'https://service.runmyaccounts.com/api/latest/clients/apitest/invoices?api_key=d1bvbxkI8f1bnMBJ4sZiC-xupl4fOEzf';

fetch(proxy_url + main_url)
    .then(response => response.text())
    .then(data => console.log(data));


推荐阅读