Angular/Node/Express/Passport Cross Domain Problems - Enable CORS Passport Facebook Authentication

别说谁变了你拦得住时间么 提交于 2019-11-28 06:50:06

I was having this issue and almost reached the point where I was convinced I could find no solution, but looking at a simple tutorial again (http://mherman.org/blog/2013/11/10/social-authentication-with-passport-dot-js/) solved it for me. I was trying to make an API call from Angular to Node.js, which is going to always bring you those XMLHttpRequest errors despite what you configure on the server, CORS or not! CORS is not the fixture - if you opened your Chrome network console, you'll find that your request to Google or Facebook or whatever 3rd party site is out of your control to change - it was triggered from a 302 redirect that was sent back to your frontend, something that Angular.js or any other framework has no power to control, thus you can't really add "Access Control Allow Origin" to that request anyway.

The solution is simply to make the button or text that says "Sign In with _____" a LINK. A literal <a href="/auth/facebook"></a> link. That's it.

Of course, I also met with a lot of other stumbling blocks and gotchas in the process. I tried to not use the default middleware for passport.authenticate('facebook'), but tried to wrap it in a function(req, res, next){ ... }, thinking that would do something, but it doesn't.

Horia Ion

I had also a problem with facebook login and cors but not with Passport in NodeJS/Express, my application is java(spring mvc)+ angular. I've managed to pass over the problem modifying my initial fb login function:

$scope.loginWithFacebook = function () {
    $http({
        method: 'GET',
        url: 'auth/facebook',
        dataType: 'jsonp'
    }).success(function(data){
        console.log('loginWithFacebook success: ', data);
    }).error(function(data, status, headers, config) {
        console.log('loginWithFacebook error: ', data);
    });
}

with

$scope.loginWithFacebook = function() {
    $window.location = $window.location.protocol + "//" + $window.location.host + $window.location.pathname + "auth/facebook";
};

Hope it helps!

Create a html tag to do the GET request instead, facebook does not allow XMLHttpsRequests.

Like so: <a href="http://localhost:8080/auth/facebook">sign in with facebook</a>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!