menu

Questions & Answers

Authorization header not being sent

When I call the POST method in Angular, authorization is not sent. Strangely, when I try vanilla JS, it works. Here's the vanilla code:

fetch('https://646a-188-122-208-8.eu.ngrok.io/api/v0/changeIdTo', {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxx'
      },
      body: JSON.stringify({ "realm": "eun1", "name":"testName", "icon":1 })
 })
    .then(response => response.json())
    .then(response => {
      console.log(JSON.stringify(response));
      this.isIconChanged().then((res: any) => {console.log('test ', res)});
})

But when I use HttpClient it doesn't work, here's the code:


let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization Basic', 'xxxxxxxxxxxxxxxxxxxx');
    const httpOptions = {
      headers: headers
    }

    const body = JSON.stringify({ "realm": "eun1", "name":"testName", "icon":1 });

    this.http.post('https://646a-188-122-208-8.eu.ngrok.io/api/v0/changeIdTo', body, httpOptions)
    .subscribe((res: any) => {
      console.log('res ', res);
    }, (err: any) => {
      console.log('err ', err);
    });`

I tried different types of headers like: 
`const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxx'
  });
Comments:
2023-01-24 08:42:02
a header with a key of "Authorization" and the value starting with "Basic", and a header with the key of "Authorization Basic" are not equivalent.
2023-01-24 08:42:02
As per linked answer, the HttpHeaders is immutable, so you need to re-assign the returned object to your local variable.
Answers(0) :