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:
-= 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.
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:
--== More Information ==--
If I send the request from Postman it works. Here's the request from Postman:
And here's what comes through Node:
Here's my request in Angular:
And here's what comes through Node:
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 }));