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

618
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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