2017-09-14 57 views
0

我有一个api。如果你打开你应该输入用户名和密码。我想获得那个api中的数据怎么样? ,如果我写get(“.... api-url ....”)它显示未经授权的错误。我怎样才能通过该API传递用户名和密码?如何通过角度传递用户名和密码与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

我假设你想把它作为查询参数与GET请求一起发送?

这是可怕的坏习惯(用户密码的URL的一部分 - 而正文内容可以通过SSL进行保护,实际的URL将是完全可见的攻击者) - 阅读更多@https://www.fullcontact.com/blog/never-put-secrets-urls-query-parameters/

而且, HTTP模块已被弃用 - 看看使用HttpClientModule代替(https://angular.io/guide/http

如果您仍然想这样做:

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

对于后:

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

GET请求一个更好的办法是在标头中发送令牌:

public getMyBlog(token) { 
    const headers = new HttpHeaders().set('Authorization', token); 
    return this.http.get('...apiurl...', { headers }); 
} 
+0

我没有从API获取数据。 –

+0

它是你自己的API吗?还是公共的?如果公开,这是什么? – yusijs

+0

它的activiti rest api –

0

使用``然后你可以在你的字符串,而不是“”。 也请尝试在发送密码之前先对密码进行加密。

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

相关问题