0

There are various questions related to the same concept, but somehow I am not able to figure out a simple HTTP Get call with Angular 2.

I have tried the same service with postman and it works, but not with a angular service.

My code looks like:

Service.js

let headers = new Headers({ 'Authorization': 'Basic ' +  btoa('[email protected]:password') });
let options = new RequestOptions({ headers: headers });

return this.http.get(Config.Api.GetNavbar, options).map((res: Response) => res.json());

I get a 401 Unauthorized error even if I am setting the headers.

Any help?

4
  • If it works with postman, then it's also easy with Angular, just make sure you send the same headers, etc. Commented Dec 7, 2016 at 9:36
  • Yes I have added the same headers. Am I missing something? Commented Dec 7, 2016 at 9:55
  • Make sure that the Authorization header value you are providing to API is valid as you are getting Unauthorized error meaning that at server side header value is checked and its Invalid Commented Dec 7, 2016 at 9:58
  • 1
    Of course you are missing something, otherwise it would work. But there is no way to guess what exactly is missing. Commented Dec 7, 2016 at 11:21

1 Answer 1

2

I was facing exactly the same behavior when I was doing my first REST calls with Angular - it worked with Postman but didn't with Angular.

Some Browsers make a so called "preflight" call before the "real" AJAX call, and this first call caused the 401 Unauthorized response. The issue was that I was not allowing OPTIONS headers without authentication. The handling of OPTIONS headers was also in the restricted area but the authentication information was missing so the server send me back a 401 Unauthorized.

In the end the solution was to handle the OPTIONS requests outside of the restricted area. So the client receives now an OK for OPTIONS headers requests and goes on with the "real" call.

Since I have adjusted the request handling on server side everything works as expected.

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.