Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
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 Respuestas
Responde la pregunta

0

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

over 4 years ago · Santiago Trujillo Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda