Reputation: 131
I'm having difficulty with getting CORS to work. I'm trying to fetch data from a Heroku app I set up. I'm fetching from Redux, and using ExpressJS for the backend. I've been looking through the CORS docs but still can't figure it out. enter link description here
This is how it looks in Express
var express = require('express');
var router = express.Router();
var cors = require('cors')
router.options('/', cors())
router.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
router.get('/', cors(), function(req, res, next) {
res.json({...})
}
I have the proxy set up in my app to http://localhost:3001/, but my app is running on 3000. I'm including this in case it could be the issue, but I don't know that it is.
My Redux file is set up like this
return dispatch => {
const url = "https://app-name.herokuapp.com/users";
return fetch(url, {
method: 'GET',
mode: 'cors',
headers: { 'Content-Type': 'text' }
})
The full error is: "Failed to load https://app-name.herokuapp.com/users: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access."
Upvotes: 0
Views: 1122
Reputation: 6261
var express = require('express');
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,POST");
// res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
Upvotes: 0