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