身份验证标头的角度HTTP拦截器

时间:2020-02-21 14:51:44

标签: javascript angular typescript angular-http-interceptors

我必须为每个HTTP请求在“授权”标头中放置一个令牌。 因此,我已经开发并注册了HttpInterceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(public authService: AuthService) {
  }  

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let modifiedReq;
    const token = this.authService.getToken();

    // we need the heck clone because the HttpRequest is immutable
    // https://angular.io/guide/http#immutability
    if (token) {
      modifiedReq = request.clone();
      modifiedReq.headers.set('Authorization', `Bearer ${token}`);
    }

    return next.handle(modifiedReq ? modifiedReq : request).pipe(tap(() => {
        // do nothing
    },
    (err: any) => {
    if (err instanceof HttpErrorResponse) {
      if (err.status === 0) {
        alert('what the heck, 0 HTTP code?');
      }
      if (err.status !== 401) {
        return;
      }
      this.authService.goToLogin();
    }
  }));
 }
}

但是标头似乎永远不会放在发送的请求上。我在做什么错了?

此外,有时拦截器会捕获到错误代码“ 0”;什么意思?

角度8.2.11

编辑1:------------------------

我也尝试过这样:

request = request.clone({
            setHeaders: {
                authorization: `Bearer ${token}`
            }
        }); 

,但仍未设置标题。 另外,该模块已在app.module中正确注册

 providers: [{
   provide: HTTP_INTERCEPTORS,
   useClass: TokenInterceptor ,
   multi: true,
 }..

编辑2:------------------------

debugger

检查这张图片...我要疯了。

3 个答案:

答案 0 :(得分:0)

也许您忘记输入app.module

  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor ,
    multi: true,
  }..

最后一部分是这样写的:

 return next.handle(modifiedReq);

答案 1 :(得分:0)

像这样对我有用:

return ListTile(
  title: Container(
    margin: EdgeInsets.all(8.0),
    padding: EdgeInsets.fromLTRB(210, 0.0, 0.0, 0.0),
    decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(
            color: Colors.pink[800], // set border color
            width: 3.0), // set border width
        borderRadius: BorderRadius.all(
            Radius.circular(10.0)), // set rounded corner radius
        boxShadow: [
          BoxShadow(
              blurRadius: 5,
              color: Colors.black,
              offset: Offset(0.5, 1))
        ] // make rounded corner of border
        ),
      child: Row(
          children: <Widget>[
            selectedItem = selectedIndex ?
        Container(
            color: Colors.red,
            child: Text(
              document['rep'],
              style: TextStyle(
                fontSize: 50.0,
                color: Colors.black,
              ),
            ),
        ) :
            Container(
              color: Colors.white,
            child: Text(
                document['rep'],
                style: TextStyle(
                fontSize: 50.0,
                color: Colors.black,
                    ),
                ),
            ),
          ]
      ),
  ),

  onTap: () {
    Firestore.instance.runTransaction(
            (transaction) async {
      DocumentSnapshot freshSnap =
      await transaction.get(document.reference);
      await transaction.update(freshSnap.reference, {
        'votes': freshSnap['votes'] + 1,
      });
    });

    setState(() {
      selectedItem = selectedIndex;
    });


  },

);

答案 2 :(得分:0)

我错了。更新克隆请求时,angular会将新标头放置在名为“ lazyUpdate ”的字段中,而不是直接放在标头内部。 由于其他原因,请求失败。

相关问题