1

I have an API. If you open that you should enter username and password. How can I get the data which is in that API? If I write get("....api-url...."), it shows unauthorized error. How can I pass a username and password to that API?

constructor(private _http: Http) { this.getMyBlog(); } private getMyBlog() { return this._http.get('http://localhost:8088/.../...') .map((res: Response) => res.json()) .subscribe(data => { this.data = data; console.log(this.data); }); } 

2 Answers 2

6

I'm assuming you want to send it along with the GET request as query parameters?

This is terrible bad practice (the users password is part of the URL - while the body contents may be protected by SSL, the actual URL will be fully visible to attackers) - read more @ https://www.fullcontact.com/blog/never-put-secrets-urls-query-parameters/

Also, the HTTP Module is being deprecated - look at using the HttpClientModule instead (https://angular.io/guide/http)

If you still want to do this:

 public getMyBlog(username, password): Observable<any> { const params = new HttpParams().set('username', username).set('password', password); return this.http.get('...apiurl...', { params }); } 

For post:

 public getMyBlog(username, password): Observable<any> { const body = { username, password }; return this.http.post('...apiurl...', body); } 

A better way for get requests is to send a token in the headers:

 public getMyBlog(token) { const headers = new HttpHeaders().set('Authorization', token); return this.http.get('...apiurl...', { headers }); } 
Sign up to request clarification or add additional context in comments.

4 Comments

I'm not getting data from api.
Is it your own API? Or a public one? If public, which is it?
Its activiti rest api
There are docs @ activiti.org/userguide/#_installation_and_authentication - basically you do:this.http.get(http://${username}:${password}@apiurl)
0

Use `` and then you can make around your string instead of ''. Also try to do something to encrypt your password before sending it.

public getMyBlog(username, password): Observable<any> { return this._http.get(http://localhost:8088/${username}/${password}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.