gpt4 book ai didi

angular - 使用 angular2 发送身份验证凭据

转载 作者:太空狗 更新时间:2023-10-29 18:31:42 24 4
gpt4 key购买 nike

我是 angular2 的新手,我正在尝试使用通过 http header 传递的 auth 凭据向本地 API 发出 REST 请求;我得到以下代码:

        let headers = new Headers();
headers.append('Accept', 'application/json')
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Basic ' + btoa(user + ":" + password));
let options = new RequestOptions({ headers: headers, withCredentials: true });

return this.http.get("http://localhost:8080/api/test-credentials", options);

但我收到 401:未经授权。如果我尝试使用 POSTMAN 一切正常,生成的 base64 编码 token 是相同的,这就是请求的对象:

[
"http://localhost:8080/api/test-credentials",
{
"method":null,
"headers":{
"Accept":[
"application/json"],
"Content-Type":["application/json"],
"Authorization":["Basic dXNlcjpwYXNzd29yZA=="]
},
"body":null,
"url":null,
"search":null,
"withCredentials":true,
"responseType":null
}
]

最佳答案

像这样发出带有身份验证的请求:

  public getRequestWithBasicAuth(url: string, data): any {

let headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("Authorization", "Basic " + data);

let requestoptions = new RequestOptions({
method: RequestMethod.Get,
url: url,
headers: headers
});

return this.http.request(new Request(requestoptions))
.map((res: Response) => {
let jsonObj: any;
if (res.status === 204) {
jsonObj = null;
}
else if (res.status === 500) {
jsonObj = null;
}
else if (res.status === 200) {
jsonObj = res.json()
}
return [{ status: res.status, json: jsonObj }]
})
.catch(error => {
return Observable.throw(error);
});
}

然后在提交登录时调用上面的函数:

  onLogin(formData) {
let url = this.global_service.base_path + 'something...';
let data = btoa(formData.email.toLowerCase() + ':' + formData.password);

this.global_service.getRequestWithBasicAuth(url, data)
.subscribe(res => {
if (res[0].status == 200) {
// Do what you want after login..
}
}
}

关于angular - 使用 angular2 发送身份验证凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com