Angular 2 http header not set

I set my header and http call as follows:

 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 expect the title 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 get the following (without authorization with a 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:

General information:

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

Thus, the OPTIONS call does not work. In other applications, once the OPTIONS call is accepted, it makes a GET request, where you can set the authentication token set. This means that for some reason OPTION is not accepting it.

When making calls using CURL or SOAP UI, it works fine, so I suppose this is not a problem with CORS. I'm right?

Any idea or guide will really be helpful.

+4
source share
4 answers

http://restlet.com/blog/2015/12/15/understanding-and-using-cors/, :

. , CORS, , , OPTIONS . OPTIONS . , .

, OPTION .

0

, headers.append, headers.set. , .

+1

:

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

append:

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

:

Since I do not know how you process your request, I can show you the solution that I found 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 is “OPTIONS”, than you can set the response status to 200, and everything will be done.

+1
source

Add this line to your security configuration:

.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
0
source

Source: https://habr.com/ru/post/1669181/


All Articles