How to fix 'Fetch request to https:www.google.com fails with CORS'
By FoxLearn 11/5/2024 2:12:10 AM 32
While the response shows a 200 status code in the developer tools, the `fetch` request always fails, triggering the error handler, and a CORS (Cross-Origin Resource Sharing) error is logged in the console. This suggests that although the server is responding, the browser is blocking the request due to security policies related to CORS.
For example:
function checkInternetConnectivity(){ fetch('https://www.google.com', { method: 'HEAD' }) .then((response) => { console.log("connected"); }, (err) => { console.log("error: " + err); }) }
To bypass CORS issues in a `fetch` request, you can set the `mode` to `'no-cors'`. This allows the request to complete without enforcing CORS restrictions, though it limits access to the response (you won't be able to read the response body or headers). Additionally, using a `HEAD` request instead of `GET` may help save bandwidth, as it only retrieves headers without the actual response body.
function checkInternetConnectivity(){ fetch('https://www.google.com', { method: 'HEAD', mode: 'no-cors' }) .then((response) => { console.log("connected"); }, (err) => { console.log("error: " + err); }) }
- How to get datatype in JavaScript
- How to convert string to boolean in Javascript
- How to Check Internet Connection Status in Javascript
- How to download file using JavaScript
- How to get selected option in JQuery
- How to get data attribute JavaScript
- How to Convert a String to an Integer in JavaScript
- How to use getday in Javascript