当尝试用JS解析一个fetch承诺时,根据这个答案将模式设置为“no-core”。 然而,将模式设置为“corse”会导致:
CORS策略阻止了从源“http://localhost:3000”在“{endpoint}”获取数据的访问:请求的资源上不存在“Access-Control-Allow-Origin”标头。 如果不透明响应满足您的需要,请将请求的模式设置为“no-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
}));
});
}
这将导致以下错误uncapted(in promise)syntaxError:
,但没有进一步的消息。 我做错了什么?return response.json()
的意外输入结束
如果一个不透明的回应满足你的需要
它不是。 你想看看反应。 你看不到不透明的响应(这就是不透明响应的意思)。
no-cors
模式意味着,如果浏览器必须做任何需要CORS许可的事情,它将静默失败,而不是抛出错误。
因此,它静默地无法获得响应,然后尝试将其解析为JSON(这会抛出一个不同的错误)。
你需要:
no-cors
模式有关CORS的更多信息,请参阅本问题。