首页 > 解决方案 > 拦截器不添加标头来获取请求

问题描述

我做了这个拦截器:

import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';

export class AddHeaderInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Clone the request to add the new header
        if (req.url.includes('GetFriend')){
        req = req.clone({
            setHeaders: {
                'Content-Type' : 'application/json; charset=utf-8',
                'Accept'       : 'application/json',
                'Authorization': `Bearer ${sessionStorage.getItem("token")}`
                }
        });

        return next.handle(req);
    }

        return next.handle(req);
    }
}

该提供商:

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

这就是获取请求,需要标头:

this.http.get('http://localhost:52575/api/account/GetFriends').subscribe((res: FriendsList)=>{
    this.friends = res;
});

我查看了 Fiddler,我向服务器发送了哪些包,没有关于添加的标头的任何信息,服务器向我发送此错误“HTTP/1.1 401 Unauthorized”:

标签: angularhttp-headersinterceptor

解决方案


推荐阅读