How to fix 'Fetch request to https:www.google.com fails with CORS'

By FoxLearn 11/5/2024 2:12:10 AM   32
You are attempting to make a simple `fetch` GET request to `https://www.google.com` to check internet connectivity.

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);
  })
}