我一直在尝试多种方法来访问使用基本身份验证的 API。问题是 Angular 2 无法输入用户名和密码。
如果您导航到基本身份验证网站,它会要求您输入用户名和密码,然后在大多数浏览器上单击登录
或取消
。如果您在此网站上单击“取消”,它将返回一个字符串,内容为“用户按下了取消”,而这正是我通过 Angular 的 HTTP 请求得到的结果。
在这个阶段,授权 header 中的编码用户名和密码是否正确并不重要,我只需要能够发送用户名和密码并让它尝试登录。
有什么建议吗?
request() {
let headers = new Headers();
headers.append('Authorization', "Basic dWRpZDM6cGFzc3dvcmQ=");
this.http.get('http://localhost:8888/api/', {
headers: headers
})
.subscribe(
data => this.example = data.text(),
err => this.logError(err.text()),
() => console.log('Request Complete')
);
console.log(this.example);
}
最佳答案
使用用户名和密码添加授权应该会有所帮助。请尝试以下操作:
let username : string = 'username';
let password : string = 'password';
let headers = new Headers();
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Content-Type", "application/x-www-form-urlencoded");
this.http.get('http://localhost:8888/api/', {
headers: headers
}).subscribe(
data => this.example = data.text(),
err => this.logError(err.text()),
() => console.log('Request Complete')
);
console.log(this.example);
希望这有帮助。
关于javascript - Angular 2 - HTTP 基本身份验证请求无法输入详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121316/