Chris Hansen
Chris Hansen

Reputation: 8647

Now allowed by cors when implementing facebook authentication

I have the following code

// in index.js

var whitelist = ['http://localhost:3000', 'http://localhost:4000',]
var corsOptions = {
    origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
            callback(null, true)
        } else {
            callback(new Error('Not allowed by CORS'))
        }
    }
}
app.use(cors(corsOptions));

// in user.js

router.get('/facebook', passport.authenticate('facebook'));
router.get('/facebook/callback', passport.authenticate('facebook', {
    failureRedirect: `/error`
}), (req, res) => {
    res.send(`/myhome`);
});

// on the frontend I have the following link in my ReactJS application

<div className="row">
   <a href="http://localhost:4000/user/facebook">Log in with Facebook</a>
</div>

When the user clicks on the link, they get the error Error: Not allowed by CORS. I have a nodejs backend at localhost:4000 that's connected to the reactjs frontend at localhost:3000. Unfortunately, when I go to http://localhost:4000/user/facebook, I get the error "Error: Not allowed by CORS".

What am I doing wrong?

Upvotes: 0

Views: 45

Answers (1)

Ahmed Hosny
Ahmed Hosny

Reputation: 470

to bypass CORS policy origin error all you need is to install 'cors' package and use it like this :-

const cors = require('cors');
app.use(cors());

NB: additional configurations like which origin to unblock and other staffs are all optional the above code will do the work !

Upvotes: 1

Related Questions