Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 http not setting header

Tags:

I'm setting my header and http call like this:

 var headers = new Headers();
headers.set('Authorization','Bearer xxxxxxxxxxx'); 

this.http.get('http://localhost:8080/outputEndpoints', {
  headers: headers
}).
map(res => res.text())

.subscribe(
  data=> console.log(data),
  error=> console.log("Getting Error") 
);

With this I'm expected the header to be:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:es,ca;q=0.8,en-GB;q=0.6,en;q=0.4,fr;q=0.2
Access-Control-Request-Headers:authorization, content-type
Authorization: "Bearer xxxxxxxxxxxx"
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:3000
 Referer:http://localhost:3000/
 User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36    (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36

Instead I'm getting the following (no Authorization with the token):

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:es,ca;q=0.8,en-GB;q=0.6,en;q=0.4,fr;q=0.2
Access-Control-Request-Headers:authorization, content-type
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36   (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

EDIT:

The general info is:

Request URL:http://localhost:8080/outputEndpoints
Request Method:OPTIONS
Status Code:401 
Remote Address:[::1]:8080

So the OPTIONS call is failing. In other apps, once the OPTIONS call is accepted it makes the GET request in where you can find the Authentication token setted. That means that for some reason the OPTION call it's not being accepted.

When making calls with CURL or SOAP UI it works fine so I presume that it's not a problem with CORS. I'am right?

Any idea or guide would be really helpful.

like image 334
ZanattMan Avatar asked Feb 08 '17 16:02

ZanattMan


2 Answers

I think it is headers.append and not headers.set. Try to change your method and see if it works.

like image 144
Jorawar Singh Avatar answered Sep 24 '22 10:09

Jorawar Singh


You should either set the value in the constructor of the Header like this:

var headers = new Headers({'Authorization', 'Bearer XXXXXXX'});

or you have to use the append method:

var headers = new Headers();
headers.append('Authorization', 'Bearer XXXXXX');

Edited due to changed question:

Since I do not really know how you handle your request I can show you the solution I came up with in my Spring backend:

if ("OPTIONS".equals(request.method, ignoreCase = true)) {
    response.status = HttpServletResponse.SC_OK
} else {
    chain.doFilter(req, res)
}

So in your backend you should check the request method and if it equals "OPTIONS" than you can set the response status to 200 and you are done.

like image 25
Deutro Avatar answered Sep 25 '22 10:09

Deutro