0

I get problems when using angularjs $http in a CORS request, my success function authenticateSuccess(data, status, headers) get wrong headers. As we know, every CORS request will be twice in angularjs, I get twice response from server, the first time is the cors validation information, the second is needed response, but my success function get the headers in the first response. But it's data is from second response.

function login(credentials) {

        var data = {
            username: credentials.username,
            password: credentials.password,
            rememberMe: credentials.rememberMe
        };
        console.log(data);
        return $http.post('//localhost:8080/api/authenticate', data).success(authenticateSuccess);

        function authenticateSuccess(data, status, headers) {
            console.log(headers());
            console.log(data);
            var bearerToken = headers('Authorization');
            if (angular.isDefined(bearerToken) && bearerToken.slice(0, 7) === 'Bearer ') {
                var jwt = bearerToken.slice(7, bearerToken.length);
                service.storeAuthenticationToken(jwt, credentials.rememberMe);
                return jwt;
            }
        }
    }
2
  • The $http .success handler is deprecated. Use .then instead. docs.angularjs.org/api/ng/service/$http#deprecation-notice Commented Jul 27, 2016 at 2:13
  • yep, I have changed it using .then. but I get the same problems, the headers is from the first time response, the data is from the second time response. Commented Jul 27, 2016 at 2:28

1 Answer 1

0

You are getting this problem as header which you are sending is not matched with the headers in backend

So let suppose In frontend you sending headers

contentHeaders = new Headers(); contentHeaders.append('Authorization', 'your token'); contentHeaders.append('Content-Type', 'application/json'); contentHeaders.append('Access-Control-Allow-Origin', '*');

So those headers like 'Authorization','Content-type', 'Access-Control-Allow-Origin' should matched with your header allow in backend.

So in backend 'Access-Control-Allow-Headers' should have all above headers see below

res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Authorization,content-type,Access-Control-Allow-Origin");

So here in Access-Control-Allow-Headers you have to passed all headers which you send from frontend : 'Authorization','Content-type', 'Access-Control-Allow-Origin'.

It will work perfectly when you use above concept.

Thanks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.