Javascript 将模式设置为';时使用fetch访问API时出错;无cors';
当尝试使用JS解析获取承诺时,根据设置将模式设置为Javascript 将模式设置为';时使用fetch访问API时出错;无cors';,javascript,cors,fetch-api,Javascript,Cors,Fetch Api,当尝试使用JS解析获取承诺时,根据设置将模式设置为'no-cors'。但是,将模式设置为'cors'会导致: 取 “{endpoint}” 源于http://localhost:3000'已被CORS策略阻止: 请求的服务器上不存在“Access Control Allow Origin”标头 资源。如果不透明的响应满足您的需要,请设置请求的 模式设置为“无cors”,以获取禁用cors的资源 所以我在函数中写了这个: search() { return fetch(`${baselin
'no-cors'
。但是,将模式设置为'cors'
会导致:
取
“{endpoint}”
源于http://localhost:3000'已被CORS策略阻止:
请求的服务器上不存在“Access Control Allow Origin”标头
资源。如果不透明的响应满足您的需要,请设置请求的
模式设置为“无cors”,以获取禁用cors的资源
所以我在函数中写了这个:
search() {
return fetch(`${baselink}${summonerEndpoint}${summoner}${apikey}`, {mode: 'no-cors'}).then(response => {
return response.json()
}).then(jsonResponse => {
console.log(jsonResponse);
if (!jsonResponse.info) {
return [];
}
return jsonResponse.info.items.map(info => ({
id: info.id,
accountId: info.accountId,
name: info.name,
profileIconId: info.profileIconId,
revisionDate: info.revisionDate,
summonerLevel: info.summonerLevel
}));
});
}
这将导致以下错误Uncaught(in promise)SyntaxError:return response.json()
的输入意外结束,但没有进一步的消息。我做错了什么
如果一个不透明的回答符合你的需要
没有。您希望看到响应。您无法看到不透明的响应(这就是不透明响应的含义)
无cors
模式意味着,如果浏览器必须执行任何需要cors许可的操作,它将以静默方式失败,而不是抛出错误
因此,它在静默中无法获得响应,然后尝试将该内容解析为JSON(这会引发另一个错误)
你需要:
- 不使用
无cors
模式
- 使用CORS授予权限的服务器
看