Fetch from local python aiohttp server

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

This can be a problem if you are trying to run a local website with a local http server (let’s say a python server with aiohttp) for testing purposes. Your fetch will probably looks like that:

fetch("http://localhost:8000/")
.then(function (response) {
return response.json();
})
.then(function (myJson) {
document.querySelector("#test").innerHTML = myJson.status;
})
.catch(function (error) {
console.log("Error: " + error);
});

but this isn’t gonna work if you don’t set the right headers in your http server. So, all you have to do is to add these headers to every server reponse:

HEADERS = {'Access-Control-Allow-Origin': "*",
'Access-Control-Allow-Headers': "*"}

With aiohhtp you can add it just like that:

return web.Response(text=json.dumps(respons_obj),
headers=HEADERS,
status=200)

Leave a Reply

Your email address will not be published. Required fields are marked *