将模式设置为 'no-cors' 时使用 fetch 访问 API 时出错
Error when accessing API with fetch while setting mode to 'no-cors'
当尝试使用 JS 解决获取承诺时,根据 this answer 将模式设置为 'no-cors'
。但是,将模式设置为 'cors'
会导致:
Access to fetch at
'{endpoint}'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
所以我在函数中这样写:
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
}));
});
}
这导致 return response.json()
出现以下错误 Uncaught (in promise) SyntaxError: Unexpected end of input
,但没有进一步的消息。我做错了什么?
If an opaque response serves your needs
没有。你想看到响应。你看不到不透明的响应(这就是不透明响应的意思)。
no-cors
模式意味着如果浏览器必须执行任何需要 CORS 许可的操作,它将静默失败而不是抛出错误。
所以它默默地没有得到响应,然后试图将什么都没有解析为 JSON(这会引发不同的错误)。
你需要:
- 不使用
no-cors
模式
- 要使用 CORS 授予权限的服务器
见。
当尝试使用 JS 解决获取承诺时,根据 this answer 将模式设置为 'no-cors'
。但是,将模式设置为 'cors'
会导致:
Access to fetch at '{endpoint}' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
所以我在函数中这样写:
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
}));
});
}
这导致 return response.json()
出现以下错误 Uncaught (in promise) SyntaxError: Unexpected end of input
,但没有进一步的消息。我做错了什么?
If an opaque response serves your needs
没有。你想看到响应。你看不到不透明的响应(这就是不透明响应的意思)。
no-cors
模式意味着如果浏览器必须执行任何需要 CORS 许可的操作,它将静默失败而不是抛出错误。
所以它默默地没有得到响应,然后试图将什么都没有解析为 JSON(这会引发不同的错误)。
你需要:
- 不使用
no-cors
模式 - 要使用 CORS 授予权限的服务器
见