gpt4 book ai didi

javascript - 从 Http (ng2) 升级到 HttpClient (ng6) 后登录请求的未定义响应

转载 作者:行者123 更新时间:2023-11-30 20:26:59 25 4
gpt4 key购买 nike

从 Angular 的 Http 升级到 HttpClient 后,我似乎无法访问对我的登录请求的响应。这是 Http 的工作代码:

login(username: string, password: string): Observable<boolean> {

let headers: Headers = new Headers();
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Content-Type", "application/x-www-form-urlencoded");

return this.http.post('http://localhost:8080/oauth/login', '', {headers: headers, withCredentials: true})
.map((response: Response) => {
if (response.status === 200) {
localStorage.setItem('setCookie', resHeaders.get("Set-Header"));
window.location.href = "http://localhost:8080/oauth/authorize?client_id=api&response_type=token&redirect_uri=http://" + document.location.host + "/%23/token//%3F";
return true;
}
else {
return false;
}
});
}

这是我用于 HttpClient 的代码:

  login(username: string, password: string): Observable<boolean> {

let httpHeaders : HttpHeaders = new HttpHeaders()
.set("Authorization", "Basic " + btoa(username + ":" + password))
.set("Content-Type", "application/x-www-form-urlencoded");

return this.http.post('http://localhost:8080/oauth/login', '', {headers: httpHeaders, withCredentials: true})
.pipe(
map(res => { // res: undefined
if (res) {
console.log("res: " + res);
}
else {
console.log("Didn't get any response");
}
})
)
}

HttpClient 代码的输出是没有得到任何响应HttpClient Docs像我上面的代码一样使用管道,但是如果我像使用 Http 一样使用 .map,那么 res 也是未定义的。我检查了 Chrome 中的实际请求和响应,它们与使用 Http 的工作代码相同。所以我知道问题是我在尝试访问响应对象时做错了什么。

最佳答案

您现在必须使用订阅函数来访问您的 Response 对象。

请注意,您现在将返回一个订阅对象。尝试这样的事情:

return this.http.post('http://localhost:8080/oauth/login', '', {headers: httpHeaders, withCredentials: true})
.subscribe(res => {
console.log("res: " + res);
},
error => {
console.log("error" + error);
}

);

关于javascript - 从 Http (ng2) 升级到 HttpClient (ng6) 后登录请求的未定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50792044/

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