Angular 7-HttpInterceptor不向请求添加标头

问题描述:

我正在尝试向所有请求添加Authorization标头,并且遇到了一些问题.即使我添加了标题,在进行网络调用时也没有使用标题.

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`
        }
      });

@Logan 尝试一下,

用户和您的token都不是必需的.

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);