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

238
Visualizações
How to fix cors error faced even with cors setup on the backend

I have configured my code in this manner on my express backend and have the cors library installed.

I am however getting this error:

Access to fetch at 'mybackend.com' from origin 'domain1.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

How can I solve this?

My backend and frontend code are as below respectively

const allowedDomains = [
    'domain 1',
    'domain 2',
    ];
app.use(cors(
     {
     origin: function (origin, callback) {
     if (allowedDomains.indexOf(origin) != -1) {
     callback(null, true);
     } else {
     callback(new Error(`Access has been blocked `));
     }
     },
     credentials: true,
     }
    ));
await fetch(`mybackend.com' ,{
     method:'GET',
     headers: new Headers({
     'Content-Type':'application/json',
     'Authorization':`Bearer ${token}`,
     }),
     body:null,
     })
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As per my limited understanding of Fetch API and CORS, I think you have to add mode: 'cors' as well as the header Access-Control-Allow-Origin: '*' or Access-Control-Allow-Origin: 'mybackend.com'. After doing that, your await fetch(...) block would look something like this.

fetch(URL, {
  mode: 'cors',
  method:'GET',
  headers: {
    'Access-Control-Allow-Origin':'*',
    'Content-Type':'application/json',
    'Authorization':`Bearer ${token}`,
  },
  body:null,
})
  .then(response => response.json())
  .then(data => { ... });

Hope this helps!

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