Angular/Node/Express/Passport - Issues when connec

2019-01-26 16:47发布

问题:

i'm trying to use facebook authentication on my NodeJs server. i came to the tutorial of http://scotch.io/ and have it working locally when using a REST client(Postman, etc).

To improve the UI i used Angular JS as a front end. but when i call a http.get to my specific route given on the NodeJs back-end i get the following error in chome and firefox:

XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…0%2Fapi%2Fauth%2Ffacebook%2Fcallback&scope=email&client_id=3000000000006. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8080' is therefore not allowed access.

i've tried several solutions on StackOverflow but its still not working... my NodeJs uses Express 4.* and a CORS middleware. for Angular i found several ways to enable CORS, none working so far.

I hope you can help me:D Thanks in advance!

回答1:

You can use 'window.location="http://localhost:3000/auth/facebook"'; in your Angular Controller from where you send the request to your Express Server which contains passport.authenticate stuff.

This will stop your angular to call facebook auth dialogue page as AJAX request.

It works for me!



回答2:

I'm using Angular with Node/Express as well, and the following function works for me with my own backend services (I'm currently not using it with Facebook to be honest), so just check it out:

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Access-Control-Allow-Origin');
    res.header("Access-Control-Max-Age", "86400"); // 24 hours

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }
};

Then, you need to use it tin the app.confiure()method as follows:

// configure Express
app.configure(function() {
   app.use(allowCrossDomain);
    ...
});

It's important to use it BEFORE all other directrives!