护照Facebook策略,使用AJAX触发路由

Passport Facebook Strategy, trigger route with AJAX

本文关键字:路由 AJAX 使用 Facebook 策略 护照      更新时间:2023-09-26

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

如果我单击错误中的链接,我会被自动处理并以 json 格式取回数据。如果我删除客户端js路由器,一切正常。但我正在尝试构建一个 SPA 应用程序。

我没有使用任何特定的前端框架,我使用熨斗导向器路由器并生成带有车把的视图。

在客户端:

 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);
    });

在服务器中.js

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

尝试将其添加到服务器:

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

这似乎是一个 cors 问题:

请尝试以下操作:

$ npm install cors

然后,在您的服务器中.js:

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

有关 cors 模块的更多详细信息:https://www.npmjs.com/package/cors

在CORS和Ajax上:http://www.bennadel.com/blog/2327-cross-origin-resource-sharing-cors-ajax-requests-between-jquery-and-node-js.htm