Passport Node.js CORS 错误

Posted

技术标签:

【中文标题】Passport Node.js CORS 错误【英文标题】:Passport Node.js CORS error 【发布时间】:2015-03-09 17:08:26 【问题描述】:

我已经尝试了一百万种方法来让护照与我的应用程序一起使用,但无济于事。每次尝试登录每个提供商(Facebook、Google、Twitter、Microsoft)都会导致类似这样的错误:

XMLHttpRequest cannot load https://www.google.com/accounts/o8/ud?openid.mode=checkid_setup&openid.ns=h…2F%2Ftest.sl%2Fauth%2Fgoogle%2Freturn&openid.realm=http%3A%2F%2Ftest.sl%2F. 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://test.sl' is therefore not allowed access.

我的应用程序没有那么复杂,这里是我的服务器代码的摘要。

var express = require('express');
var ppGoogle = require('passport-google-oauth').OAuth2Strategy;
var app = express();

app.use(bodyParser.urlencoded( extended: false ));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
//There's more config

app.listen(7230);

app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/return', passport.authenticate('google', 
   successRedirect: '/main',
   failureRedirect: '/login'
));

passport.use(new ppGoogle(
    clientID: '',
    clientSecret: '',
    callbackURL: 'http://test.sl/auth/google/return'
,
function (accessToken, refreshToken, profile, done)

    console.log('done');
));

有人知道解决办法吗?这件事快把我逼疯了。

【问题讨论】:

这个错误是从哪里来的?一开始就不应该这样做。 抱歉没有指定,这是客户端,浏览器正在尝试进行身份验证。 发出 AJAX 请求的堆栈跟踪是什么?什么客户端代码在这样做? 这一切都由 Passport 自动完成。我不知道细节。客户端只是向 /auth/google 发送一个 GET 请求 错了;您需要导航到该 URL,而不是 AJAX 请求它。 【参考方案1】:

您正在尝试通过 AJAX 而不是页面导航加载 Google 的 OAuth 提示。

您应该用普通导航替换您的 AJAX 请求,

【讨论】:

以上是关于Passport Node.js CORS 错误的主要内容,如果未能解决你的问题,请参考以下文章

Node.js 和 Passport 对象没有方法 validPassword

WSO2IS + node.js passport-saml 集成错误

在我的 express 中为 node.js 设置了 cors 但仍然给出关于 cors 的相同错误

Post 请求 Node.js 和 React 的 CORS 错误

在使用 node.js 和 Express 构建的 api 中使用 cors 中间件时出现 CORS 错误

Passport.js 和 MongoStore 错误“在 MongoStore 找不到连接策略”