2

我有一个 nodejs (express) 作为服务器端,一个 angular 6 作为客户端。在服务器中,我有中间件功能,可以进行会话检查。如果会话无效或不存在,我想向客户端发送响应,以便它可以对其做出反应。我想从服务器返回一个 401 的响应代码,并在客户端制作某种 listener\route-guard\HttpInterceptor,这样 - 它可以管理客户端中的情况(例如,将其重定向到登录页面) . 这是我在服务器中的代码:

router.use('/', (req, res, next) =>
{
    if (!req.session.user)
    {
        res.status(401);
    }
    else{
        next();
    }
})

如何在 Angular 应用程序中捕捉\收听此响应?

4

3 回答 3

5

您可以创建一个HttpInterceptor可以检查状态是否为 401,如果是,则注销用户并重定向到登录页面。做什么HttpInterceptor是拦截每个请求和响应,并允许您执行一些特定操作,例如检查 servce 是否返回 401 状态。但是请注意它的工作原理range,如果您将其包含在顶级模块中,那么它将拦截每个请求和响应interceptorservices

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor( 
       private authService: AuthService
    ) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => event), // pass further respone
            catchError((error: HttpErrorResponse) => {
                // here will be catched error from response, just check if its 401
                if (error && error.status == 401)
                    // then logout e.g. this.authService.logout()
                return throwError(error);
            }));
    }
}

然后将其包含app.httpmodule在提供者部分

providers: [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true
  },
]

在angular.io 文档angular.io 指南中阅读更多信息

于 2019-06-19T09:14:25.560 回答
2

当您点击 http 调用时,会出现两个参数。第一:成功回调。第二:错误回调。

例如,如果我们有一个名为 api下面的服务将是完整的代码:

如果您需要捕获服务中的错误:

 getData(){ 
  this._http.get(url).map((response: Response) =>{
     return response.json();    
   })
     .catch(this.handelError) 
}

handelError(error: Response){
   console.log('got below error from server',error);
}

如果您需要捕获组件中的错误:

 someMethod(){

    this._apiService.getData().susbscribe((result)=>{
         console.log('sucess',result);
        // do further processing
    },(error)=>{
        console.log('error from service',error);
        // do further processing
     });
}
于 2019-06-19T09:16:00.010 回答
-1

如果您使用的是 Angular Js,那么您可以试试这个

Angular Js 代码

$http.get(url).then(function(response){
  console.log(response.status); //successful status like OK
}, function(response){
  console.log(response.status); //error status like 400-Bad Request
})

response.status这将为您提供状态代码。

如果您使用的是 Angular 2 或更高版本,那么您可以试试这个

Angular 2/更高的代码

sendForgotPass() {
 return this.service.postForgotPass(this.emailFormControl.value)
    .subscribe(
      res => {
        console.log(res.status);
      })
    }

res.status这将给出状态码

于 2019-06-19T09:13:09.447 回答