2017-06-20 77 views
0

我需要使用基本身份驗證進行http獲取請求,但我不知道如何。我正在使用ionic2,角色爲& typescript。 我的代碼:如何在Ionic內的http獲取請求中使用useBasicAuth?

this.http.get("http://address") 
    .map(res => res.json()) 
    .subscribe(data =>{ 
     console.log(data); 
    }); 

從離子文檔我看到我需要什麼,但我是新來的這些技術,我不能夠使用它:useBasicAuth(username, password)

我已經嘗試了這些解決方案,但它沒有工作:Angular 2- Http POST request parameters

編輯

我一直在努力之下

012碼
let headers = new Headers(); 
headers.append('Content-Type', 'application/json'); 
headers.append('Authorization', 'Basic xxxxxxx='); 

let options = new RequestOptions({ headers: headers }); 

this.http.get("http://VLCwebServerAddress",options) 

甚至

this.http.get("http://VLCwebServerAddress",headers)

如果第二個參數是我得到的迴應401,所以驗證失敗。

如果第二個參數是選項我得到Response for preflight has invalid HTTP status code 501其中I've read它與服務器端的CORS有關。

回答

0

我終於明白了。我是混合角和Ionic2-cordova庫。

我沒有注意到,我不得不使用import { HTTP } from '@ionic-native/http';

而是採用import { Http, HttpModule } from '@angular/http';

(這是我在教程和其他問題看到的代碼)然後,我能夠使用列出的所有方法http documentation for Ionic2

請記住該插件在運行時不起作用ionic serve yourApp在瀏覽器上,但在真實設備上運行應用程序時。

我重新檢查並嘗試了多次使用http角度庫進行請求,但只要向請求中添加了額外內容(如標頭),就會停止工作(不確定是否因爲服務器) 。謝謝你的答案。

0

當登錄成功時,您需要將用戶名和令牌存儲在sessionstorage或localstorage中。那麼您需要將它們發送到您的請求的標題中。

getUserByName(username: string) { 
let url="http://localhost:8088/rest/user/userName"; 
let header=new Headers({'Content-Type': 'application/json', 'Authorization': localStorage.getItem("token")}); 

return this.http.post(url, username, {headers: header}); 

}

+0

我「找不到getUserByName」如果我嘗試你的代碼。 我想知道如何使用文檔中定義的「getBasicAuthHeader(username,password)」,但沒有使用示例。 –

+0

你對基本編程有什麼想法嗎?我寫的代碼需要保持服務。 –

+0

我很容易被卡住......不過,我想我已經理解了你的代碼,並試圖按照你在編輯中看到的方式來實現。但仍然沒有成功。日Thnx。 –

0

只需簡單地追加一個首標;

let headers = new Headers(); 
headers.append('Authorization', 'Basic' + btoa('username' + ":" + 'password')); 
this.http.get(url, { headers: headers }); 
0

隨着你的RequestOptions添加下面的參數

withCredentials: true