My usecase : I am trying to make a simple fetch GET request to https://www.google.com to check for the internet connectivity. I need to check the response code and depending upon that, decide if user is having internet connectivity. Now though I can see a 200 code (with no response headers or response) in the developer tools, the fetch always fails landing into the error handler for the fetch call and the console flags the CORS error.
I do understand since I am making a cross origin request so this should lead to CORS error.
I want to know what can I do to get my connectivity code working. I can't obviously alter google.com's response headers. The reason for using google.com for this is because of it's reliability, just like we hit google.com in browser mostly to check if internet is working or not :D
My code :
networkMonitor: () => {
const headers = new Headers();
headers.append('Cache-Control', 'no-cache');
const timerId = setInterval(() => {
fetch('https://www.google.com')
.then((response) => {
if (response.status != 200) {
// Yay ! connected
}
}, (err) => {
console.log("error: " + err); // (currently fetch failed)
})
}, 5000);
}
P.S : I know there is no way to disable the same origin policy or force the other site to send the allow all origin headers. This can though be bypassed by using a cors proxy. I want to know that can google.com or similar readily available sites be used to verify connectivity by my way or not, and if not, then is there some other way to deal with them from the point of view of just getting connectivity information.
http://connectivitycheck.gstatic.com/generate_204instead. Also made by Google, but created to check if you have a valid connection. Make sure to compare against status code 204. Fetching google.com returns unnecessary data and takes 90ms, whereas gstatic returns nothing and takes 30ms