Sunday, 1 September 2019

CORS issues. Github pages -> Heroku

I'm running into classic cors issue, that I cannot solve.

Access to XMLHttpRequest at 'xxx/current_user' from origin 'https://username.github.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I obviously installed cors in my Node.js app and use proper headers. Here's how my index.js looks like:

const express = require('express');
const cors = require('cors')
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const cookieSession = require('cookie-session');

const keys = require('./config/keys');


require('./models/user');
require('./services/passport');

mongoose.connect(keys.mongoUri, { useNewUrlParser: true })

const app = express();

app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(
    cookieSession({
        maxAge: 30 * 24 + 60 * 60 * 1000, //30 days
        keys: [keys.cookieKey]
    })
);

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

app.use(passport.initialize());
app.use(passport.session());

//ROUTES
require('./routes/auth')(app);
require('./routes/game')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);

And my basic test call to API inside my react app looks like this:

export const checkAuth = () => dispatch => {
    axios.get('/current_user').then(res => {
        if (res.data) {

        }
    }).catch(err => {
        console.log({ err })
    })
}

Am I missing something obvious?

Headers for 1st request

Headers for 2nd request

Code for current_user route

 app.get('/current_user', (req, res) => {
        res.send(req.user)
    })



from CORS issues. Github pages -> Heroku

No comments:

Post a Comment