Passport Facebook策略,使用AJAX触发路线 [英] Passport Facebook Strategy, trigger route with AJAX

查看:34
本文介绍了Passport Facebook策略,使用AJAX触发路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: XMLHttpRequest无法加载https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…lhost%3A8080%2Fapi%2Fauth%2Ffacebook%2Fcallback&client_id=1527429390857121.所请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许访问来源"http://localhost:8080".

如果我单击错误中的链接,我将得到警告并获取json中的数据.如果我删除客户端js路由器,一切正常.但是我正在尝试构建SPA应用程序.

If i click the link in the error i get autenticated and get back the datas in json. If i remove the clientside js router everithing works fine. But i am trying to build a SPA app.

我不使用任何特定的前端框架,而是使用 flatiron director 路由器,并使用把手.

I don't use any specific frontend framework, I use flatiron director router and generate the view with handlebars.

在客户端:

 var facebook = function () {
        console.log('GET /auth/facebook');

        $.ajax({
        url: '/api/auth/facebook',
        type: 'get',
        dataType: 'jsonp',
        cache: false
       });
    };

// ROUTES ===============================
var routes = {
    ...
    '/auth': {
        '/facebook' : facebook,
        '/twitter' : twitter,
        '/google': google
    },
    ...
};

在服务器端:

    // send to facebook to do the authentication
    router.get('/auth/facebook', passport.authenticate('facebook'));

    // handle the callback after facebook has authenticated the user
    router.get('/auth/facebook/callback', function(req, res, next) {
        passport.authenticate('facebook', function (err, user, info) {
            if (err) return next(err);
            if (!user) return res.status(403).json(info);

            req.logIn(user, function (err) {
                if (err) { return next(err); }
                return res.json({user: user, message: info});
            });
        })(req, res, next);
    });

在server.js中

in server.js

...
app.use('/api', router);
...

推荐答案

尝试将其添加到服务器:

Try to add it to server:

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    next();
});

这篇关于Passport Facebook策略,使用AJAX触发路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆