2

I'm having a problem setting my JWT in the header for my requests. Here's how I'm building the request:

const headers = { 'x-access-token' : this.token };
const config = { headers: headers };
return this.http.get(this.allStudentsUrl, config)
    .toPromise()
    .catch((error) => this.handleError(error))
    .then((response) => this.handleStudents(response));

When I step through this looks perfect but it's coming through the server with the token. On the server the headers look like this:

Server results

-= Edit =-

To answer some questions, I actually started out using the Headers and RequestOptions classes and that was giving me strange results so I switched to using object literals to try to simplify. This is what I had:

let headers = new Headers();
headers.append('x-access-token', this.token);
let config = new RequestOptions({ headers: headers });
return this.http.get(this.allStudentsUrl, config)
    .toPromise()
    .catch((error) => this.handleError(error))
    .then((response) => this.handleStudents(response));

But when I append the token to the header it just repeats the key in the value. Here's a screen shot of the debug window.

Debug WAT

As you can see, even thought I set the key as x-access-token and the value as the token (which I inspected to verify that it's actually the token) the header has x-access-token as both the key and the value.

I can verify that the token is the correct token by inspecting it as well. Here's a screenshot of that:

Look at that token!

--== More Information ==--
If I send the request from Postman it works. Here's the request from Postman:

Postman

And here's what comes through Node:

Postman Result

Here's my request in Angular:

Angular Request

And here's what comes through Node:

Angular Result

CaseyB
  • 24,780
  • 14
  • 77
  • 112
  • can you try using angulars Headers & RequestOptions classes (https://blogs.msmvps.com/theproblemsolver/2016/12/16/angular-2-and-http-request-headers/) – LLai Jun 23 '17 at 19:03
  • @LLai I started out this way and ran into the same issue. This was a result of my trying to simplify. Please see my edit. – CaseyB Jun 23 '17 at 20:14
  • 1
    where is this.token set? Is it possible it is the same string 'x-access-token'? – LLai Jun 23 '17 at 20:18
  • It's set when I authenticate the user. It's not the same string. I'll post a picture. – CaseyB Jun 23 '17 at 20:27
  • that debug window you posted is right. the _normalizedNames only contains the header keys. If you look in _headers you should see the actual value – LLai Jun 23 '17 at 20:54
  • You right! I can see the token in the _headers map but it's still not coming through to my server. It shows `access-control-request-headers: "x-access-token"` but never has the actual token value. – CaseyB Jun 23 '17 at 21:17
  • Does it work if you use headers.set('x-access-token', this.token) instead of headers.append? – Rob Zuber Jun 23 '17 at 22:29
  • It does not. It does the same thing. – CaseyB Jun 24 '17 at 17:30
  • It is a long shot, but can you reinstall your node_modules? Maybe an angular library got corrupted. Can you also try passing in some other header, to see if it doing the same thing on any header or if it just the x-access-token header. – LLai Jun 26 '17 at 14:09
  • I deleted my node_modules folder and reinstalled them all. That didn't work. So then I tried adding more headers and I saw that no matter what I added, or how many they got added under `access-control-request-headers` when I looked at them on the server side but the headers aren't actually there. – CaseyB Jun 30 '17 at 18:43
  • There's an excellent article about JWT token that you should read, it might help https://medium.com/@amcdnl/authentication-in-angular-jwt-c1067495c5e0 – maxime1992 Jul 04 '17 at 08:43

3 Answers3

3

you need create options like

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization': 'Bearer ' + this.token);

let options = new RequestOptions({ headers: headers });

return this.http.get(this.allStudentsUrl, options);
CharanRoot
  • 6,181
  • 2
  • 27
  • 45
1

Backend:

First you need to configure your backend server to send these headers in the response:

Access-Control-Allow-Headers:x-access-token
Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:x-access-token

Front end: Initialize the headers :

const headers = new Headers({'Content-Type': 'application/json; charset=utf-8'});
const options = new RequestOptions({headers: headers});

Adding jwt/other custom headers :

options.headers.set('x-access-token', 'my-token'));
options.headers.set('additional-info', 'my-info'));   

http Request :

this.http.post(url, body, options)
        .subscribe((res: Response) => {
      // Write custom code here
}
this.http.get(url, options)
        .subscribe((res: Response) => {
      // Write custom code here
}
Deepak Kumar
  • 1,669
  • 3
  • 16
  • 36
1

For those who stumble upon this (most likely including myself in another six months) here is what the problem was:

Because I was adding custom headers to the request the browser first sent a CORS OPTIONS request to see if the server would be willing to accept a GET request. I wasn't doing anything special with that request and the browser didn't know how to interpret the response so it didn't send the actual GET request. This is why I saw my headers in the access-control-request-headers field. The browser was trying to ask the server if those headers were ok before it sent any actual data. I fixed it by handling CORS in my server with this code:

const cors = require('cors');
app.use(cors({ origin: '*', optionsSuccessStatus: 200 }));
CaseyB
  • 24,780
  • 14
  • 77
  • 112