首页 > 解决方案 > 如何以角度返回整个 HTTP 响应以查看特定的响应标头?

问题描述

我正在尝试在我的 Angular 应用程序中检查特定的响应标头。如果用户尝试使用过期的 JWT 访问需要有效 JWT 的路由,则来自后端 ASP.NET Core 服务器的响应标头具有token-expired: true. 我想在将用户发送到刷新路线之前检查该值。

我尝试了以下方法来查看整个响应标头,但没有成功:

`public fetchPosts(): Observable<HttpResponse<Object>>  {
    var b = this.http.get<HttpResponse<Object>>('api/v1/posts', {observe: 'response'}).pipe(
      tap(resp => console.log('THE RESPONSE FOR FETCH POSTS IS:', resp))
    )
    console.log('THIS IS VALUE OF B: ', b);
    return b;
  }`

的值b始终是这样的:

`
Observable {_isScalar: false, source: Observable, operator: DoOperator}
post.service.ts:20
_isScalar:false
operator:DoOperator {nextOrObserver: , error: undefined, complete: undefined}
complete:undefined
error:undefined
nextOrObserver:function (resp) { … }
[[FunctionLocation]]:internal#location
[[Scopes]]:Scopes[2]
arguments:TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
caller:TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
length:1
name:""
prototype:Object {constructor: }
`

我知道我需要在后端服务器上专门公开某些响应标头,但是b对象具有未定义的errorcomplete键的事实让我想知道我是否真的做错了什么?

任何见解将不胜感激。

标签: angularobservable

解决方案


Http 响应及其标头是当 HttpClient 从服务器接收到错误响应时作为错误事件发出的,如指南中所述。因此,您只需要在订阅(或使用tap()or catchError())时提供一个错误处理程序。

.pipe(
    catchError(error => {
        const responseHeader = error.headers.get('<header_name>');
        if (responseHeader) {
            // send to /refresh-token route
        }
    })
)

推荐阅读