【发布时间】:2014-11-19 16:45:06
【问题描述】:
在 NodeJS/Express 中尝试使用 Passport 对 Facebook 用户进行身份验证时,已有 100 万人尝试启用 CORS。
我在 Chrome 上遇到的错误是这样的:
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…%3A8080%2Fauth%2Ffacebook%2Fcallback&scope=email&client_id=598171076960591.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
我使用的路线就这么简单:
// =====================================
// FACEBOOK ROUTES =====================
// =====================================
// route for facebook authentication and login
app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/home',
failureRedirect : '/login'
}));
这是在我的 angularJS 文件上调用路由的方式(我也尝试过设置 withCredentials : true):
$http.get('/auth/facebook')
.success(function(response) {
}).error(function(response){
});
我尝试了十几种解决方案,这些解决方案是在 StackOverflow 和其他论坛上找到的。
-
我尝试在 routes.js 文件的路由之前添加此内容:
app.all('*', function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header("Access-Control-Allow-Headers", "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name"); res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS'); res.header('Access-Control-Allow-Credentials', true); if ('OPTIONS' == req.method) { res.send(200); } else { next(); } }); -
我尝试在 server.js 文件中添加它(请注意,我将 header 更改为 setHeader,但我都尝试过):
app.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With'); res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS'); res.setHeader('Access-Control-Allow-Credentials', true); if ('OPTIONS' == req.method) { res.send(200); } else { next(); } }); require('./app/routes.js')(app, passport); -
我尝试在我的 app.js 文件中添加这个(angularJS 配置):
$httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; $httpProvider.defaults.withCredentials = true;
不管怎样,我不知道还能做什么。我在网上找到的所有东西都不起作用。 是否有可能与我使用 AngularJS 路由有关?我看不出这有什么重要的原因,但我有点猜不透了。
我的情况和这个很相似: Angular/Node/Express/Passport - Issues when connecting to facebook(CORS)
提前致谢!
【问题讨论】:
-
我知道有很多类似的问题,而且我几乎都看过。不幸的是,到目前为止,我尝试过的解决方案都没有奏效......
-
您不能同时使用
Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: *'。对于您的情况,您应该设置Access-Control-Allow-Origin: localhost:8080而不是*。 -
嗨@LarissaLeite,你有没有让这个与anguar一起工作?我现在正在尝试,但遇到了您的问题。
-
@LarissaLeite 你找到解决方案了吗?你发布这个已经两年了,但我现在面临这个问题。谢谢
标签: angularjs node.js cors passport.js passport-facebook