Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served.
Sources : MDN - HTTP Access Control | Wiki - CORS
CORS is set server-side by supplying each request with additional headers which allow requests to be requested outside of the own domain, for example to your localhost. This is primarily set by the header:
Allow-Control-Allow-OriginThe header specifies which origins (domains/servers) the information can be accessed from. To enable CORS you usually set it to allow access from all origins with a wildcard (*):
Allow-Control-Allow-Origin: *If you have Chrome you can use a extensions which 'hacks' the request. Be sure to disable it when not testing as it can break other sites.
Allow-Control-Allow-Origin: * @ Chrome Web Store
All who uses your site must use this hack so this is only intended for bypassing temporarily and for testing during development. You can't assume it will work for your end users.
You can bypass CORS in production using JSONP which stands for JSON with Padding and is kinda also a 'hack'. But it is a widely used hack which many APIs support. You are not sending a pure JSON-request but you are wrapping your data in a function that gets evaluated. JSONP explained in the link below:
JSONP explained in layman terms @ Stack Overflow
The simplest way to handle JSON is through the $.ajax()-function in jQuery as it handles the real dirty parts automatically:
$.ajax({
method: 'GET',
url: 'http://localhost:3000',
dataType: 'jsonp', //change the datatype to 'jsonp' works in most cases
success: (res) => {
console.log(res);
}
})There is no native implementation of JSONP in either XMLHttpRequest or fetch. If you want to use fetch you can use this 1kb library which handle JSONP with fetch:
- Link the code in your
index.html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.0.6/fetch-jsonp.min.js"></script>- And use like fetch but with the function
fetchJsonp:
fetchJsonp('http://localhost:3000')
.then(res => res.json())
.then(json => console.log(json));We are entering backend territory, be aware. You can redirect the traffic from your choosen API through your own node-server and this will allow you to set the headers that control CORS yourself. You can set up a node-server that makes a request to to the API via the package request for you. Instructions are in the repository in the link below.
This will allow you to make your calls to http://localhost:8000 instead of the API-URL.