javascript - 如何在不告诉 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();
解决方案
它似乎被黑了但是......工作:使用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));
推荐阅读
- python - 在 Python 输出上使用 Bash“测试”运算符?
- svelte - 如何在 Svelte 中禁用组件挂载和销毁的过渡动画?
- google-apps-script - 关于简单代码的表单提交触发器,但有两个表单链接到 Google 表格电子表格
- angular - 导入的库 - 模拟方法和排除
- leaflet - 迭代 Leaflet 标记簇组并更新标记的标题
- python - 在 Mac OS X 中找不到模块 Pyperclip 的已安装版本
- swift - SwiftUI - 在 AVPlayer 中添加播放速率控制
- eclipse - 包括 OpenSSL for eclipse 在内的问题
- twitter - 结果的第二页发回相同的 next_token
- c - iovec 的 iov_len 字段是否定义明确?