【问题标题】:Passport Facebook Strategy, trigger route with AJAXPassport Facebook 策略,用 AJAX 触发路由
【发布时间】:2023-03-06 15:40:02
【问题描述】:

问题: 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 应用程序。

我不使用任何特定的前端框架,我使用flatiron director 路由器并使用把手生成视图。

在客户端:

 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 中

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

【问题讨论】:

  • 已经有一段时间了,但是你有什么运气吗?你找到解决办法了吗?

标签: javascript node.js express facebook-authentication passport.js


【解决方案1】:

尝试将其添加到服务器:

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

【讨论】:

    【解决方案2】:

    这似乎是一个cors问题:

    尝试以下方法:

    $ npm install cors

    然后,在你的 server.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

    【讨论】:

    • 您好,很遗憾我仍然遇到同样的错误。如果我关闭前端路由并在没有 ajax 的情况下直接点击 url,它就像一个魅力。
    猜你喜欢
    • 2015-07-27
    • 2018-03-05
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2018-07-31
    相关资源
    最近更新 更多