Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何在Ionic中的http get请求中使用useBasicAuth?_Angular_Ionic2_Basic Authentication - Fatal编程技术网

Angular 如何在Ionic中的http get请求中使用useBasicAuth?

Angular 如何在Ionic中的http get请求中使用useBasicAuth?,angular,ionic2,basic-authentication,Angular,Ionic2,Basic Authentication,我需要使用基本身份验证发出http get请求,但我不知道如何进行。我正在使用ionic2、angular和typescript。 我的代码: 从Ionic文档中,我看到了我需要的东西,但我对这些技术不熟悉,无法使用它: 我尝试过这些解决方案,但都不起作用: 编辑 我一直在尝试下面的代码 let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authoriz

我需要使用基本身份验证发出http get请求,但我不知道如何进行。我正在使用ionic2、angular和typescript。 我的代码:

从Ionic文档中,我看到了我需要的东西,但我对这些技术不熟悉,无法使用它:

我尝试过这些解决方案,但都不起作用:

编辑

我一直在尝试下面的代码

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响应,因此身份验证失败


如果第二个参数是options I get
Response for preflight具有无效的HTTP状态代码501,它与服务器端的CORS相关。

登录成功时,您需要将用户名和令牌存储在会话存储或本地存储中。然后,您需要在请求的标题中发送它们

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});

}

只需添加一个标题

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

我终于明白了。我把angular和Ionic2 cordova库搞混了

我没有注意到我必须使用
从'@ionic native/HTTP'导入{HTTP}

而不是从'@angular/Http'使用
import{Http,HttpModule}

(这是我在教程和其他问题中看到的代码)然后,我能够使用

请记住在浏览器上运行应用程序时,此插件不起作用,但在真实设备上运行应用程序时,此插件不起作用


我已经用http angular库重新检查并尝试了几次执行请求,但只要我向请求添加额外的内容(如标题),它就会停止工作(不确定是否是因为服务器)。感谢您的回答。

与您的请求选项一起添加以下参数

withCredentials: true

如果我尝试你的代码,我会得到“找不到getUserByName”。我想知道如何使用文档中定义的“getBasicAuthHeader(username,password)”,但没有使用示例。你对基本编程有什么想法吗?我写的代码需要继续使用。我很容易被卡住。。。尽管如此,我认为我已经理解了您的代码,并尝试实现您在编辑中看到的功能。但仍然没有成功。Thnx。
withCredentials: true