Angular 4拦截器未设置标头

时间:2018-08-30 17:48:28

标签: angular

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const jwt = localStorage.getItem('jwt');
if (!jwt) {
  req = req.clone(
    {
      headers: req.headers.set('Authorization', 'Bearer ' + jwt)
    });
}
console.log(req);
return next
  .handle(req)
  .do(evt => {
    if (evt instanceof HttpResponse) {
    }
  })
  .catch(err => {
    return Observable.throw(err);
  });

}

这是我的感应器课, 在chrome请求中看起来像这样: chrome screenchot

CURL看起来像这样(从chrome devtools复制):

curl "http://192.168.10.220:8090/api/portal/getMojeRezerwacjeList" -X 
OPTIONS 
-H "Access-Control-Request-Method: GET" 
-H "Origin: http://localhost:4200" 
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" 
-H "Access-Control-Request-Headers: authorization" --compressed

显然没有带Bearer和jwt令牌的标头, 我一直都遇到401错误

1 个答案:

答案 0 :(得分:0)

尝试使用setHeaders而不是标头

const newRequest = req.clone({               setHeaders:{'Authorization':'Bearer'+令牌}