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

246
Visualizações
Fetch problem with node.js express server

I'm having some trouble with the fetch and node.js. In my frontend when i click a button, i would like to send a post request in order to receive an array from my backend as answer. I'n my backend i'm using node.js with express, in my frontend i'm using the fetch function.

The error that occours is the following:

Access to fetch at 'http://localhost:8080/api' from origin 'real localhost address' 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.

Code Here

const getArray = async() => {
  const data = await fetch ("http://localhost:8080/api");
  const dataJson = await data.json();
  console.log(dataJson)
}

getArray(); 

In my server i've got

app.post("/api", (req,res) => {
    res.sendFile(JSON.stringify(arr));
});
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You need to add request options. Please refer to the MDN docs for further information.

over 4 years ago · Santiago Trujillo Relatório

0

As @Kudah said, you should read the docs.

Fetch (and XMLHttpRequest) follow the same-origin policy. This means that browsers restrict cross-origin HTTP requests from within scripts. A cross-origin request occurs when one domain (for example http://example2.com/) requests a resource from a separate domain (for example http://example1.com/).

The easiest way to solve this, (If you don't want to dig too much into this)

const whiteList = [ "https://myRealBackendUrl-1", "https://myRealBackendUrl-2" ];
// you can also pass a string here instead here instead of array
const corsOptions = {
  credentials: true,
  origin: process.env.NODE_ENV !== production ? "http://localhost:4000" : whiteList
  // if you are in a dev environment, you probably want something like localhost
  // http://localhost:4000 is just a demo backend. replace it with your own.
  // if you are in a production environment, for example heroku then your backend 
  // url will be something like http://example.herokuapp.com 
  // in that case `const whiteList = [ "http://example.herokuapp.com" ];`
};

app.use(cors(corsOptions));

The above code should be enough for the normal use case.

There is also callback function, it is if you want to run some function of your own. Don't read it if you dont plan to use any dynamic checking

var corsOptionsDelegate = async (req, callback) => { 
    var corsOptions = { origin: false };
    try {
        // you can do some dynamic check here
        // For example: check database for some conditions then allow access
        if( myDatabaseSays == true ) corsOptions.origin = true;
        else corsOptions.origin = false;
    } catch (err) {
        console.log(err);
        // corsOptions.origin = false;
    }
    callback(null, corsOptions) // chain it
}

Anyway read the docs properly for more info [1]: https://expressjs.com/en/resources/middleware/cors.html

over 4 years ago · Santiago Trujillo 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