Angular 7-HttpInterceptor不向请求添加标头 [英] Angular 7 - HttpInterceptor not adding header to request

查看:117
本文介绍了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);

这篇关于Angular 7-HttpInterceptor不向请求添加标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆