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

617
Vistas
Error No 'Access-Control-Allow-Origin' - Nodejs

I'm developing an api taking data from a json file that will be inside the project's local files.

I'm having a problem with requests on the front end to get the data, it's a cors error.

In the api I believe I enabled the headers correctly, but I don't know if I have to do it on the front and how I have to do it.

Below will be my code from the index.js file and then the script.js file that will serve to get the data from the api

Main api file that has cors

const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");

// Routes
const routeLogin = require('./routes/login');
const routeRegister = require('./routes/register');
const routeHashtags = require('./routes/hashtag');

const app = express();



// Use
// Morgan
app.use(morgan("dev"));

// Body parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors
app.use((req, res, next) => {
  res.header("Access-Control-Allow-credentials", "true");
  res.header("Acces-Control-Allow-Origin", "*");
  res.header(
    "Acces-Control-Allow-Header", 
    "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-CSRF-Token"
  );
  res.header('Acces-Control-Allow-Methods', "GET,OPTIONS, POST, DELETE, PUT, PATCH");

  next();
})



// Routes
app.use('/login', routeLogin);
app.use('/register', routeRegister);
app.use('/hashtag', routeHashtags);

// Error
app.use((req, res, next) => {
  const error = new Error("Erro! Não encontrato!");
  error.status = 404;
  next(error);
})

app.use((error, req, res, next) => {
  res.status(error.status || 500);
  return res.send({
    error: {
      message: error.message
    }
  })
})



module.exports = app;

Front end

async function dashboard(){
  async function pendingPosts(){
    await fetch("http://localhost:3120/hashtag/")
    .then((res) => res.json())
    .then((data) => {console.log(data)})
  }
  pendingPosts()
}
dashboard()
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You need to use

npm install cors

var cors = require('cors')

app.use(cors())

try this hope it will help to you

over 4 years ago · Santiago Trujillo Denunciar

0

install the cors dependency and then use it is a middleware

app.use(cors());

After this, if you make a request to your server, a new header will be returned as follows,

Access-Control-Allow-Origin: *

It determines which origins are allowed to access server resources over CORS.

The * wildcard allows access from any origin or if you want to allow access to particular origin then add origin option to the middleware..

app.use(cors({
  origin: 'http://localhost:3000'
}));

After this, if you make a request to your server, a new header will be returned as follows, Access-Control-Allow-Origin: http://localhost:3000

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