Error when accessing API with fetch while setting mode to 'no-cors' [duplicate]
When trying to resolve a fetch promise with JS is set the mode to 'no-cors'
based on this answer. However setting the mode to 'cors'
results in having:
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.
So I wrote this in my function:
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
}));
});
}
This results in following error Uncaught (in promise) SyntaxError: Unexpected end of input
for return response.json()
, but with no further message. What am I doing wrong?
If an opaque response serves your needs
It doesn't. You want to see the response. You can't see an opaque response (that is what opaque response means).
no-cors
mode means that if the browser has to do anything that requires permission from CORS, it will fail silently instead of throwing an error.
So it is silently failing to get the response, then trying to parse that nothing as JSON (which throws a different error).
You need:
- To not use
no-cors
mode - The server to grant permission using CORS
See this question for more information about CORS in general.