拦截器不添加标题以获取请求

时间:2019-12-09 17:56:06

标签: angular http-headers interceptor

我做了这个拦截器:

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 },
],

这是get请求,需要标头:

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

我查看了Fiddler,我将哪些包发送到服务器,没有有关添加的标头的任何信息,并且服务器向我发送了此错误“ HTTP / 1.1 401未经授权”:

0 个答案:

没有答案