How to fix 'Fetch request to https:www.google.com fails with CORS'
By FoxLearn 11/5/2024 2:12:10 AM 177
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 convert voice to text in Javascript
- LET vs VAR in JavaScript Variable Declarations
- How to add voice commands to webpage in Javascript
- How to capture an image in javascript
- How to Build Your Own JavaScript Library
- How to reverse a string properly in Javascript
- How to bypass 'Access-Control-Allow-Origin' error with XMLHttpRequest
- What is Hoisting in JavaScript