我有一个API.如果您打开,则应输入用户名和密码.如何获取该API中的数据?如果我写get("....api-url...."),它显示unauthorized error.如何将用户名和密码传递给该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);
});
}
Run Code Online (Sandbox Code Playgroud)
我假设你想将它与GET请求一起作为查询参数发送?
这是一个可怕的不良做法(用户密码是URL的一部分 - 虽然正文内容可能受SSL保护,实际的URL将完全被攻击者看到) - 阅读更多@ https://www.fullcontact.com/blog /从未把-秘密的URL查询参数/
此外,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 });
}
Run Code Online (Sandbox Code Playgroud)
发布时间:
public getMyBlog(username, password): Observable<any> {
const body = { username, password };
return this.http.post('...apiurl...', body);
}
Run Code Online (Sandbox Code Playgroud)
获取请求的更好方法是在标头中发送令牌:
public getMyBlog(token) {
const headers = new HttpHeaders().set('Authorization', token);
return this.http.get('...apiurl...', { headers });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5279 次 |
| 最近记录: |