Search code examples
javascriptasync-awaitcorsfetchrest

How to perform cross-origin requests in fetch along with async await? (CORS error)


const runFunction = async () => {

try {
    const getAPI = await fetch(`https://xkcd.com/1/info.0.json`);
    const resp = await getAPI.json();

    console.log(resp);

} catch (error) {
    console.log(error);

}
}

runFunction();

I'm trying to get information from an API using fetch and async/await but I am getting a CORS error. I have tried adding multiple headers such as:

 const getAPI = await fetch(`https://xkcd.com/1/info.0.json`,
    {
        headers:
        {
            "Access-Control-Allow-Origin":"*",
            "Access-Control-Allow-Methods": "HEAD, GET, POST, PUT, PATCH, DELETE",
            "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token"
        }
    });

Doing that still gives me the error "No 'Access-Control-Allow-Origin' header is present on the requested resource". The only way I've been able to solve the problem is by adding a CORS unblock extension to my browser. I don't think thats an efficient way of going about my code because anyone accessing my project will have to download the extension.

To fix this problem, will I have to create a node app? Is there no way to fix this on the client side?


Solution

  • The Access-Control-Allow-* headers are response headers, so adding them to your request will not have any effect. The owner of xkcd.com would have to enable CORS requests on their server by adding these headers.

    There's nothing you can do to fetch client-side if the server owner has not enabled CORS.