MEAN堆栈Facebook授权错误:No' Access-Control-Allow-Origin'头?

时间:2014-10-29 17:27:29

标签: javascript facebook angularjs node.js express

我正在尝试在我的MEAN堆栈应用程序上进行facebook授权。我正在使用passportpassport-facebook。我没有使用jadeejs,我想使用纯粹的angularjs。当我运行我的应用程序并单击"登录"按钮,我收到以下错误:

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

我做了一些研究,发现节点cors模块可以解决这个问题,但它没有。

我做错了什么,我该如何解决?

这是我的routes.js文件(服务器端):

app.get('/auth/facebook', passport.authenticate('facebook'));

app.get('/auth/facebook/callback', passport.authenticate('facebook', {
    successRedirect: '/success',
    failureRedirect: '/error'
}));

app.post('/success', function(req, res, next) {
    User.findById(req.session.passport.user, function(err, user) {
        if(err){ 
            res.send({success:false}); 
        }else{ 
            res.send({success:true,user: user});
        }
    });
});

app.get('/logout', function(req, res){
    req.logout();
    res.redirect('/');
    res.end();
});

app.post('/error', function(req, res, next) {
    res.send({success:false});
});

这是我的passport.js文件(服务器端):
注意: clientIDclientSectretcallbackURL位于另一个文件(config.js)中。但它们是有效的。

passport.use(new FacebookStrategy({
    clientID: config.facebookAuth.clientID,
    clientSecret: config.facebookAuth.clientSecret,
    callbackURL: config.facebookAuth.callbackURL
    },
    function(accessToken, refreshToken, profile, done) {
        User.findOne({ oauthID: profile.id }, function(err, user) {
            if(err) { console.log(err); }
            if (!err && user != null) {
                done(null, user);
            } else {
                var user = new User({
                    oauthID: profile.id,
                    name: profile.displayName,
                    created: Date.now()
                });
                user.save(function(err) {

                    if(err) {
                        console.log(err);
                    } else {
                        console.log("saving user ...");
                        done(null, user);
                    }
                });
            }
        });
    }
));


// serialize and deserialize
passport.serializeUser(function(user, done) {
    console.log('serializeUser: ' + user._id)
    done(null, user._id);
});
passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user){
        console.log(user)
        if(!err) {done(null, user);}
        else {done(err, null)}
    });
});

这是我的快速配置文件:express.js(服务器端):

var express = require('express'),
    passport = require('passport'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    cors = require('cors');

var whitelist = ['https://www.facebook.com'];
var corsOptions = {
  origin: function(origin, callback){
    var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
    callback(null, originIsWhitelisted);
  }
};

module.exports = function (app, config) {
    app.set('view engine', 'ejs');
    app.use(cookieParser());
    app.use(bodyParser());
    app.use(cors(corsOptions));
    app.use(session({secret:"car advisor secret"}));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(express.static(config.rootPath+"/public"));
}

客户端

这是我的html文件:

<body>
    <div class="navbar-right" ng-controller="LoginCtrl">
        <form class="navbar-form" >
            <a class="btn btn-primary" ng-click="signin()" ng-show="!identity.isAuthenticated()">Sign in</a>
            <a class="btn btn-primary" ng-click="signout()" ng-show="identity.isAuthenticated()">Sign out | {{identity.currentUser.name}}</a>
        </form> 
    </div>
    <ng-view></ng-view>

这是我的登录控制器:

$scope.signin = function(username, password) {
    authService.authenticateUser(username, password).then(function(success) {
        if (success){
            console.log("You have successfully signed in!");
        }
    });
}

$scope.signout = function() {
    authService.logoutUser().then(function() {
        console.log("You have successfully signed out!");
        $location.path('/');
    });
}

这是我处理服务器通信的服务(authService.js):

carApp.factory('authService', function($http, Identity, $q, $cookieStore, $resource) {
return {
    authenticateUser: function(username, password) {
        var dfd = $q.defer();
        $http.get('/auth/facebook').
            success(function(data, status, headers, config) {
                if (data.success) {
                    Identity.currentUser = response.data.user;
                    $cookieStore.put('user', response.data.user);
                    dfd.resolve(true);
                } else {
                    $cookieStore.remove('user');
                    dfd.resolve(false);
                }
            });
        return dfd.promise;
    },
    logoutUser: function() {
        var dfd = $q.defer();
        $http.get('/logout').success(function() {
            Identity.currentUser = undefined;
            $cookieStore.remove('user');
            dfd.resolve();
        });
        return dfd.promise;
    }

3 个答案:

答案 0 :(得分:2)

我不确定这是否能解决您的问题,但我最近经历了类似的尝试让Facebook登录角色应用程序。确保在你的Facebook应用程序设置页面,

https://developers.facebook.com/apps/{your_app_id}/settings/   

更改&#34;网站网址&#34;无论您当地的主人是谁。例如:

http://localhost:8080/

答案 1 :(得分:1)

你好,我不确定这有助于你尝试

    app.config(['$httpProvider', function ($httpProvider){
      $httpProvider.defaults.useXDomain = true;
   // $httpProvider.defaults.cache = true;
      $httpProvider.defaults.withCredentials = true;
   // $httpProvider.defaults.xsrfCookieName = '';
   // $httpProvider.defaults.xsrfHeaderName = '';
      delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

答案 2 :(得分:0)

您无法向其他地址发出ajax请求。即使地址相同且端口不同,您也会遇到“相同的原始策略”问题。

您可以使用nginx并使用proxy_pass重定向请求。

检查: http://distinctplace.com/infrastructure/2013/10/14/internal-redirect-to-another-domain-with-proxy_pass-and-nginx/

类似

server
{
  listen 80; 
  server_name localhost;

  location /auth/facebook/request {
    proxy_pass http://(...)facebook.com/(...);
  }
}