0

I need to make a HTTP request in my angular solution. I have created a service with a HTTP client.

However, I can't seem to add the right headers.

Here is what the working request looks like in python :

requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'password'))

How can I 'translate' this into the right request for my example ? :

public getFile() {
  return this.http.get('https://api.github.com/user', {headers :myGetHeaders});
}
Zako
  • 151
  • 2
  • 11

1 Answers1

1

You can create a httpOptions object which is passed from httpclient as shown below. It is essentially a map in which you can define various request header.

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

Now you can do

return this.http.get('https://api.github.com/user', httpOptions );

You can refer to this and this for more details.

Yug Singh
  • 3,112
  • 5
  • 27
  • 52
  • Thank you for your help. Your answer was helpful for my code, but I still can't get my request to work properly. I need to pass my 'username' and 'password' as params somewhere. – Zako Apr 03 '19 at 14:55
  • @Zako do you mean as query params or path params? – Yug Singh Apr 03 '19 at 14:56
  • if it is query param you can use ?username='user'&password='pass'. For path params as the name suggest you can directly pass them in the path. But for security reasons you should avoid sending username and password as path params – Yug Singh Apr 03 '19 at 15:00
  • 1
    Yeah I think what's wrong is the way I'm trying to do it. I've read that it might be easier to pass a token instead of credentials. Gonna try this way : new httpHeaders({'Authorization' : 'zfkgn4432qyxnrsmdl3xdbrsf2lnsrmba4deu6vyri3mwlhbpyju', 'Content-Type': 'application/json'}); Thank you! – Zako Apr 03 '19 at 15:22