簡體   English   中英

如何使用 api 以 angular 傳遞用戶名和密碼?

[英]how to pass username and password with api in angular?

我有一個 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);
        });
}

我假設您想將它與 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);
    }

獲取請求的更好方法是在標頭中發送令牌:

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

使用`` 然后你可以圍繞你的字符串而不是''。 還可以嘗試在發送密碼之前進行一些加密。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM