Angular 7 - HttpInterceptor not adding header to request

限于喜欢 提交于 2019-12-13 20:17:01

问题


I am trying to add Authorization header to all my requests and am facing some issues. Even though I am adding the headers, the headers are not being used when network call is made.

Below is my interceptors code:

 const user: string = localStorage.getItem('user');
const token: string = localStorage.getItem('token');

const authReq = request.clone({
  headers: request.headers.set('Authorization', user + ',' + token)
});
return next.handle(authReq);

I have taken this code from angular documentation, I am not sure what I am missing here.

I've tried the following code as well, but no luck:

request = request.clone({
        setHeaders: {
          Authorization: `something`
        }
      });

回答1:


@Logan give a try to this ,

user is not required along with your token unless your implementation requires it.

const user: string = localStorage.getItem('user');
const token: string = localStorage.getItem('token');

const  clonedRequest = req.clone({
   headers: new HttpHeaders({
         Authorization: token,
         "Content-Type": "application/json"
       })
    });

return next.handle(clonedRequest);



回答2:


Use for example:

let headers = new HttpHeaders({
    'Authorization': `Bearer ${token}`,
    'another', 'somedata'
});


来源:https://stackoverflow.com/questions/54820257/angular-7-httpinterceptor-not-adding-header-to-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!