Javascript 如何在angular中获取响应头
如果摘要身份验证的错误代码为401,我将尝试从http响应获取头 这是我的代码:Javascript 如何在angular中获取响应头,javascript,angular,http,http-headers,Javascript,Angular,Http,Http Headers,如果摘要身份验证的错误代码为401,我将尝试从http响应获取头 这是我的代码: this.http.post(this.hostname + ':10000/users/auth2', { }) .subscribe(res => { console.log(res); }, error => { console.log(error); }); 如果post请求返回2
this.http.post(this.hostname + ':10000/users/auth2', { })
.subscribe(res => {
console.log(res);
},
error => {
console.log(error);
});
如果post请求返回200代码,一切正常。
如果我从后端返回401代码,我将无法访问标题
chrome调试器显示标题。邮递员呼叫也可以使用摘要身份验证。观察参数的默认选项是
body
,通过
将{observe:'response'}
添加到您的post
方法:
this.http.post(this.hostname + ':10000/users/auth2', {}, {observe: 'response'})
.subscribe(res => {
console.log(res);
},
error => {
console.log(error.headers);
});
我有一个非常类似的问题,我想从响应中获取状态代码 最后做了这样的事情:
return await this.http
.post<any>(this.hostname + ':10000/users/auth2', {})
.toPromise()
.then(res => res.data, (err:HttpErrorResponse) => err.headers);
return等待this.http
.post(this.hostname+':10000/users/auth2',{})
.toPromise()
。然后(res=>res.data,(err:HttpErrorResponse)=>err.headers);
只要error
是HttpErrorResponse
的实例,就应该能够检查标题:因为它扩展了<代码>错误。标题应该是我在请求中添加了{observe:'response'}的实例,但标题字段为空。headers:Map(0),lazyUpdate:null;normalizedNames:Map(0)我想这是Chrome控制台中的一个安全问题。我想你确实得到了标题,但是你不能把它们打印到控制台上。尝试对所需的头执行一些代码操作,并让我知道它是否有效。我尝试将响应头设置为paypload,用于新请求this.http.post(this.hostname+':10000/users/auth2',{},{},{observe:'response'})。subscribe(res=>{console.log(“TEST”);},error=>{console.log(error.headers);this.http.post(this.hostname+':10000/users/test',error.headers,{headers:error.headers}).subscribe(res=>{console.log(“test”);})
它不起作用…我用以下方法来获取特定的标题,也许这对您应该有用:res.headers.get(“”);