0

I've got a function that logs in a user, and the response gives me the token in the body, which i set in headers.

this.headers = new HttpHeaders({'Content-Type': 'application/json'});


loginUser(email, password) {
        const body = {email, password};
        return this.http.post(`${this.serverUrl}/users/login`, body, {
            observe: 'response',
            headers: this.headers
        })
            .pipe(
                tap(res => {
                    if (res.body['token']) {
                        this.jwtToken = res.body['token'];
                        this.headers.set('x-auth', this.jwtToken);
                        this.router.navigate(['/firms/create']);
                    }

                })
            );
    }

Then, when I try to use those headers to send a request for logging out, I see that the 'x-auth' header is not present. But I clearly set it in the loginUser function.

Here's my logout function:

   logoutUser() {
        return this.http.delete(`${this.serverUrl}/users/me/token`, {
            observe: 'response',
            headers: this.headers
        })
            .pipe(
                tap(res => {
                    this.headers.delete('x-auth');
                    this.removeTokenFromLocalStorage(this.jwtToken);
                    this.jwtToken = null;
                })
            );
    }

And these are the headers that I'm sending to the server on my LOGOUT call (notice how I don't have the x-auth there, although I should!)

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:
Connection:keep-alive
Content-Type:application/json
Host: censored
Origin:http://evil.com/
Referer:http://localhost:4200/somendpoint
User-Agent:

Side-note: My back-end is set up to intercept req.headers['x-auth'] and do login with that (in the auth middleware). Any help would be appreciated.

filipbarak
  • 1,835
  • 2
  • 17
  • 28
  • 1
    Possible duplicate of [Angular HttpClient doesn't send header](https://stackoverflow.com/questions/45286764/angular-httpclient-doesnt-send-header) – Ben Kolya Mansley Jan 29 '18 at 16:20

1 Answers1

2

HttpHeaders is immutable - it doesn't change, it must be reassigned.

Change the line to:

this.headers = this.headers.set('x-auth', this.jwtToken);

And in your delete function:

this.headers = this.headers.delete('x-auth');

And it should work.

Ben Kolya Mansley
  • 1,768
  • 16
  • 24
  • That solved it! Thanks. I've written applications before where I used to just set headers, didn't occur to me that the HttpHeaders was Immutable. Thanks again. – filipbarak Jan 29 '18 at 16:32