如何处理 Angular 6 中的 401 未经身份验证的错误 [英] How to handle 401 unauthenticated error in Angular 6

查看:47
本文介绍了如何处理 Angular 6 中的 401 未经身份验证的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的数据服务响应 401 状态(未经身份验证)时,我需要定向到登录页面.这是我的代码

I need to direct to login page while my data service response to 401 status(unauthenticated ).Here is my code

get_data(url,auth=true){
        //......url : url path......
        //....auth : true api auth required,false no api required....
        var get_url = API_URL + url;
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Accept', 'application/json');
        if(auth==true){
            var localStore =    JSON.parse(localStorage.getItem('currentUser'));
            if (localStorage.getItem("currentUser") != null) {
                headers.append("Authorization", "Bearer " + localStore.token);
            }else{
                headers.append("Authorization", "Bearer ");
                //this.router.navigate(['/login']);
            }
        }
        let options = new RequestOptions({ headers });
        return this.http.get(get_url, options) .pipe((map(res => res.json())));
    }

推荐答案

允许你可以在 angular 中创建一个 http 拦截器来管理发送请求和收到响应时的操作

Allow you can create an http interceptor in angular to manage action when request are sent and when you get response

http.interceptor.ts

http.interceptor.ts

import { throwError as observableThrowError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Injectable, ErrorHandler } from '@angular/core';
import { UserStore } from '../store/user.store';
import { Router } from '@angular/router';
import * as HttpStatus from 'http-status-codes';

@Injectable()
export class SimpleHttpInterceptor implements HttpInterceptor {

  constructor(private router: Router, private userStore: UserStore) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = this.addAuthentication(req);
    return next.handle(req).pipe(catchError((err) => {
      if (err.status === HttpStatus.UNAUTHORIZED) {
        this.router.navigate(['/login']); //go to login fail on 401
      }
      return observableThrowError(err);
    }));
  }

  //here you add the bearer in every request
  addAuthentication(req: HttpRequest<any>): HttpRequest<any> {
    const headers: any = {};
    const authToken = this.userStore.getToken(); // get the token from a service
    if (authToken) {
      headers['authorization'] = authToken; // add it to the header
      req = req.clone({
        setHeaders: headers
      });
    }
    return req;
  }
}

然后您可以在模块示例中注册它

You can then registrer it in a module example

@NgModule({
  imports: [
    HttpClientModule
  ],
  exports: [
    HttpClientModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: UcmsHttpInterceptor, multi: true }
  ],
})
export class RestModule {

这篇关于如何处理 Angular 6 中的 401 未经身份验证的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆