Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda