During an attempt to resolve a fetch promise using JavaScript, setting the mode to 'no-cors' based on a previous suggestion resulted in an error.
When the mode is set to 'cors,' it produces a CORS policy blocking error. As suggested, changing the mode to 'no-cors' with the intention of disabling CORS and fetching the resource opaquely resulted in an unexpected error:
Uncaught (in promise) SyntaxError: Unexpected end of input for return response.json()
The root cause of this error lies in the function:
<code class="javascript">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 })); }); }</code>
Setting the mode to 'no-cors' implies that the browser should fail silently if it encounters any CORS-related issues. In this case, the server does not grant permission using CORS and the request fails silently.
Consequently, the subsequent attempt to parse the empty response as JSON (using response.json()) throws a SyntaxError, as there is no data to parse.
To resolve this issue, there are two main requirements:
By following these steps, the application can fetch the data successfully without experiencing any CORS-related errors.
The above is the detailed content of Why Does Setting \'mode: \'no-cors\'\' Throw a SyntaxError When Using fetch?. For more information, please follow other related articles on the PHP Chinese website!