Angular 5 + Ionic 3: I can’t send headers in API requests

Asked

Viewed 356 times

0

I am consuming an API through a post method and need to command the Authorization header. I am doing it as follows:

public post(resource, body, authorization = false): Observable<any> {

    const headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');

    if (authorization) {
        let token = this.userStorageService.get('accessToken');
        headers.append('Authorization', 'Bearer ' + token);
    }

    return this.http
        .post<Observable<any>>(`${environment.apiUrl}${resource}`, JSON.stringify(body), {headers: headers})
        .map(response => response);
}

But for some reason Angular doesn’t send the headers. I’ve tried these forms, but none of them work. Does anyone have any idea what it might be?

OBS 1: I am using Angular 5 and Ionic 3 OBS 2: I’ve tried using Interceptors and it didn’t work OBS 3: I’ve debugged the request in the api by Postman, it works right there, sending the headers and everything, but the app does not work at all.

  • Already debugged the code to see if the header is being filled?

  • I’ve debugged yes man, doesn’t really send any kind of header

  • I’m facing the same problem...

2 answers

0

From what I understand, the HttpHeaders is immutable. Try this way:

Example:

const headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');

or:

const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
  • Thanks brother, but I’ve tried everything in this business, it didn’t work out. But thanks!

0

Even using the append from Httpheaders it returns a copy that must be used.

For example

const headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');

Now yes the variable headers contains the desired value.

I hope I’ve helped.

[]s

Browser other questions tagged

You are not signed in. Login or sign up in order to post.