在Angular中添加标题“授权”

时间:2019-06-20 05:43:26

标签: angular token interceptor

我想为每个请求设置标题。

我正在使用request.clone在Angular 7.2.14中设置标头

import { HttpInterceptor, HttpEvent, HttpRequest, HttpHandler, HttpResponse, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export class AuthInterceptor implements HttpInterceptor {


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {        
        const token=localStorage.getItem('token');
        console.log(token);
        request.clone({ headers: request.headers.set('Authorization', token) });    
        return next.handle(request)
    }

}


我没有收到错误,但可以看到授权标头

2 个答案:

答案 0 :(得分:4)

您正在返回未克隆的旧请求。

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('token');
    request = request.clone({
        setHeaders: {
            Authorization: `Bearer ${token}`
        }
    });

    return next.handle(request);
}

答案 1 :(得分:2)

request.clone()返回一个不改变原点的对象。

尝试通过request.clone()作为参数。

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {        
        const token=localStorage.getItem('token');
        console.log(token);    
        return next.handle(request.clone({ headers: request.headers.set('Authorization', token) });)
    }