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}); } 

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 do you mean as query params or path params?
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
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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.