I know this has been asked countless times on SO but none of the solutions I have found have worked for me.
I have a Node API connected to a MongoDB database with Express.
I am trying to return data to a React front-end but whenever I make a request to the API endopint I get the following error:
Access to fetch at 'http://redacted.com' from origin 'localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried several solutions found from previous questions around this being asked on SO but none of the solutions seem to be working for me.
I have tried the following solutions:
app.use(cors({origin: 'http://localhost:3000', methods: 'GET, POST', preflightContinue: false'}));
app.use(cors({origin: '*'}));
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin': 'http::/localhost:3000');
res.setHeader('Access-Control-Allow-Methods': 'GET, POST');
next();
app.options('*', cors());
Nothing seems to work and continues to throw this cross-origin error.
Here is my full index.js for my API:
let express = require('express');
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
const cors = require('cors');
let apiRoutes = require('./api-routes/routes');
let app = express();
var port = process.env.PORT || 3001
app.use('/api', apiRoutes)
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(cors({
origin: 'http://localhost:3000'
}))
mongoose.connect('mongodb://localhost:27017', { useNewUrlParser: true });
var db = mongoose.connection;
app.get('/', (req, res) => res.send('API is working!'));
app.listen(port, function() {
console.log("Running server on port 3001");
});
Fetch request in React:
const response = await fetch('http://localhost:3001/api/pcg/bgproutestate');
const data = await response.json();
console.log(data);
Is anyone able to please tell me what could be the issue and how to solve this? I've never had this issue with previous APIs... Thanks
CodePudding user response:
Okay as soon as I posted the question I found a solution...
If I move the following code..:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin': 'http::/localhost:3000');
res.setHeader('Access-Control-Allow-Methods': 'GET, POST');
next();
..above this code..:
app.use('/api', apiRoutes)
..It takes the cors policy and allows data to be fetched. I think the cors needs to be defined before you define the routes of your API. Hope this helps someone else!
CodePudding user response:
CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. You can try:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});