How to fix 'Fetch request to https:www.google.com fails with CORS'
By Tan Lee Published on Nov 05, 2024 235
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 use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript