Passport AngularJS ExpressJS:Access-Control-Allow-Origin不允许Origin null

当我试图使用angular.js的$ http模块来授权twitter应用程序时,我总是得到:

XMLHttpRequest cannot load https://api.twitter.com/oauth/authenticate?oauth_token=something. Origin null is not allowed by Access-Control-Allow-Origin. 

客户代码:

 $http({ method: 'GET', headers: { "Content-Type": undefined }, url: '/oauth/twitter' }); 

服务器代码:

 app.configure(function () { app.use(express.cookieParser()); app.use(express.cookieSession({ secret: 'tobo!', cookie: { maxAge: 3600 }})); app.use(express.session({secret: 'secret'})); app.use(passport.initialize()); app.use(passport.session()); }); app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Credentials", true); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header("Access-Control-Allow-Headers", 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.get('/oauth/twitter', passport.authenticate('twitter'), function (req, res) { // The request will be redirected to Twitter for authentication, so this // function will not be called. console.log('ouath/twitter') }); app.get('/oauth/twitter/callback', passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' })); 

但是,如果我使用oauth / twitter地址的超链接的话,那就行了。 我不知道是什么问题。 大多数人表示不允许来源,但'*'应该允许每个地址连接到服务器。

我有同样的问题,我find的唯一解决scheme是使用超链接(如你在你的文章中所说)。 我认为你不能使用ajax请求出于安全原因。 然而,使用超链接为我工作,我可以授权我的用户。

你为什么不使用超链接? 有什么问题吗?

您不能使用导致redirect到Twitter的AJAX请求,因为使用Twitter进行身份validation意味着实际的用户交互,用户必须login到他们的Twitter帐户并授予您的应用程序访问其部分帐户的权限。

您将不得不将浏览器的位置更改为/oauth/twitter ,或者使用该URL创build一个新窗口(并在完成身份validation时将信号发送回主窗口)。