我想将 API 调用(外部源,没有机会更改 API 端的某些内容)从 PHP 更改为 Javascript(学习目的)。
由于跨域,我使用了fetch()。当我运行脚本时,出现意外的输入错误,并且无法找出原因。
function postData(url = '', data = {}) {
var headers = new Headers();
headers.set('Authorization', 'Basic ' + window.btoa("user" + ':' + "pass"));
return fetch(url, {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrer: 'no-referrer',
body: JSON.stringify(data),
}).then(response => response.json()).catch(error => console.error(error));
}
postData('https://www.api-endpoint.com/cat1/api/search?', {
"searchID": "710",
"isTagged": true
}).then(data => console.log(JSON.stringify(data))).catch(error => console.error(error));
如何确定此代码的问题?看来授权没问题。我按照 API 开发手册中的描述实现了搜索参数(searchID 和 isTagged)。
提前致谢!
最佳答案
您说的是 mode: 'no-cors',
它会禁用所有需要 CORS 权限的内容。
由于跨源读取数据需要CORS权限,所以没有数据。
尝试将空字符串解析为 JSON 会导致输入意外结束,因为输入在任何 JSON 之前就结束了。
(请注意,需要 CORS 权限以及您尝试执行的其他操作包括将内容类型设置为 JSON 并包含凭据)。
关于javascript - 通过 fetch() 调用 API - 输入意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57727097/