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()
CodePudding user response:
You need to use
npm install cors
var cors = require('cors')
app.use(cors())
try this hope it will help to you
CodePudding user response:
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