在 NodeJS/Express 中尝试使用 Passport 对 Facebook 用户进行身份验证时,已有两天一百万人尝试启用 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 文件中添加它(请注意,我将标头更改为 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 connected to facebook(CORS)
提前致谢!