Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error No 'Access-Control-Allow-Origin' - Nodejs [closed]

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()
like image 648
Gabriel Edu Avatar asked Sep 18 '25 07:09

Gabriel Edu


1 Answers

You need to use

npm install cors

var cors = require('cors')

app.use(cors())

try this hope it will help to you

like image 160
Shivam Avatar answered Sep 19 '25 22:09

Shivam