2017-09-14 56 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}

相關問題