Fetch APIs
(and XMLHttpRequest) follow the same-origin policy. The browsers restrict cross-origin HTTP requests from within
scripts. A cross-origin request occurs when request a resource from one domain
to other domain (from domain1.com to domain2.com).
As an Example,
//
From http://domain1.com/
fetch('http://domain1/data.json')
.then(function(response) {
// Do
something with response
});
The browser only returns the response
if the server returns an Access-Control-Allow-Origin header specifying that the
origin has permission to request the resource.
Cross-Origin Warning message: - Cross-Origin Request Blocked: The Same
Origin Policy disallows reading the remote resource at http://domain1/data.json
(Reason: CORS request did not succeed).
In the Fetch APIs, we can use no-cors
mode to request opaque resources. The
cors by default.
As an Example,
fetch(url,
{ method: 'HEAD', mode: 'no-cors' })
.then(res => {
console.log(res);
if (res.ok) {
console.log('URL is exists.');
}
else {
console.log('URL does not exist.');
}
})
.catch(err => console.log('Error:', err));
Make sure you are either
making the same-origin requests or CORS is enabled on the server.
What Is fetch?
The Fetch API is a simple
interface for fetching resources. Fetch makes it easier to make web requests
and handle responses than with the older XMLHttpRequest.