I have seen this issue multiple times been posted on forum, but working out with those solutions hasn't helped.
I am building MEAN stack app using PassportJS to allow login with Twitter.
angular.module('HomeCtrl', []).controller('HomeController', function($scope,$http) {
$scope.tagline = 'To the moon and back!';
$scope.twit = function() {
console.log("twitter button clicked");
$http.get("/auth/twitter")
.success(function (data) {
console.log(data);
})
//$window.location.href = '/auth/twitter';
}});
My route.js in server has
app.get('/auth/twitter', passport.authenticate('twitter', { scope : 'email' }));
Now when the twitter redirects to the app, the server redirect doesnt work because of CORS issue, which I am able to understand. To fix this
I have tried following
app.all('/*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
next();
});
but still this doesn't work. After reading more on web my understanding is that twitter doesn't send the header-origin ,and since its a redirect so node.js server doesn't have control on the response it receives which can be sent to the browser back .
At this stage I am not sure how to proceed. Please advise
As per comment : Here is the response of twitter callback
Request URL:https://api.twitter.com/oauth/authenticate?oauth_token=l8OKcAvqr3QLrlCroweGgByvvhXfSmIiqhvRgGqML6c
Request Headers
Provisional headers are shown
Accept:application/json, text/plain, */*
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Query String Parametersview sourceview URL encoded
oauth_token:l8OKcAvqr3QLrlCroweGgByvvhXfSmIiqhvRgGqML6c
I would actually solve this in the middleware and not in the router:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
next();
});
If you intend to support all methods you can avoid declaring the method list. Also, some CORS requests require a preflight request using OPTIONS method, so you may want to consider adding that to your list (perhaps this omission is the cause of your problem since POST requests, for instance, would require a preflight request using OPTIONS).
That being said, if this is express, you can probably use a middleware like cors to make your life simpler.