5

当我尝试使用 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 地址的超链接,它可以正常工作。我不知道是什么问题。大多数人说不允许来源,但'*'应该允许每个地址都连接到服务器。

4

3 回答 3

3

我遇到了同样的问题,我发现的唯一解决方案是使用超链接(正如您在帖子中所说)。我认为出于安全原因,您不能使用 ajax 请求。但是,使用超链接对我有用,我可以授权我的用户。

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

于 2014-01-20T10:38:10.380 回答
1

您不能使用导致重定向到 Twitter 的 AJAX 请求,因为使用 Twitter 进行身份验证意味着实际的用户交互,其中用户必须登录到他们的 Twitter 帐户并授予您的应用程序访问其帐户(部分)的权限。

您要么必须将浏览器的位置更改为/oauth/twitter,要么使用该 URL 创建一个新窗口(并在身份验证完成后向主窗口发出信号)。

于 2013-11-11T17:54:36.003 回答
0

只需在客户端代码中调用您的超链接。

window.location.href=''

于 2018-07-10T07:02:53.670 回答