Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
Recuperar problema con el servidor expreso node.js

Tengo algunos problemas con fetch y node.js. En mi interfaz, cuando hago clic en un botón, me gustaría enviar una solicitud de publicación para recibir una matriz de mi backend como respuesta. En mi backend estoy usando node.js con express, en mi frontend estoy usando la función fetch.

El error que da es el siguiente:

El acceso para buscar en 'http://localhost:8080/api' desde el origen 'dirección de host local real' ha sido bloqueado por la política de CORS: No hay un encabezado 'Access-Control-Allow-Origin' en el recurso solicitado. Si una respuesta opaca satisface sus necesidades, establezca el modo de la solicitud en 'no-cors' para obtener el recurso con CORS deshabilitado.

Código aquí

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

En mi servidor tengo

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

0

Necesita agregar opciones de solicitud. Consulte los documentos de MDN para obtener más información.

over 4 years ago · Santiago Trujillo Report

0

Como dijo @Kudah, deberías leer los documentos.

Fetch (y XMLHttpRequest) siguen la política del mismo origen. Esto significa que los navegadores restringen las solicitudes HTTP de origen cruzado desde los scripts. Una solicitud de origen cruzado ocurre cuando un dominio (por ejemplo, http://example2.com/ ) solicita un recurso de un dominio separado (por ejemplo, http://example1.com/ ).

La forma más fácil de resolver esto, (si no quieres profundizar demasiado en esto)

 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));

El código anterior debería ser suficiente para el caso de uso normal.

También hay una función de devolución de llamada, si desea ejecutar alguna función propia. No lo lea si no planea usar ninguna verificación dinámica

 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 }

De todos modos, lea los documentos correctamente para obtener más información [1]: https://expressjs.com/en/resources/middleware/cors.html

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!