Passport AngularJS ExpressJS: Origin null is not allowed by Access-Control-Allow-Origin

我怕爱的太早我们不能终老 提交于 2019-12-22 06:19:21

问题


When I'm trying to use $http module of angular.js for authorizing twitter app I always get:

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

Client Code:

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

Server Code:

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' }));

But it works ok if I use a hyperlink with oauth/twitter address. I don't know what is the problem. Most said that origin is not allowed, but '*' should allow every address to be connected to server.


回答1:


I had the same problem and the only solution that I have found is to use an hyperlink (as you say in your post). I think that you can't use a ajax request for security reason. However using an hyperlink worked for me and I can authorize my users.

Why don't you use an hyperlink? Is there some problem?




回答2:


You can't use an AJAX request that results in a redirect to Twitter, because authenticating with Twitter means actual user interaction, where the user has to log on to their Twitter account and grant your app access to (parts of) their account.

You're going to either have to change the browsers' location to /oauth/twitter, or create a new window with that URL (and signal back to your main window when authentication is done).




回答3:


Just call your hyperlink in client code.

window.location.href=''



来源:https://stackoverflow.com/questions/19910160/passport-angularjs-expressjs-origin-null-is-not-allowed-by-access-control-allow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!