vue——接口修改请求头——有些接口不需要请求头传递token——基础积累

最近在写后台管理系统的时候,遇到一个切换租户的功能。在请求接口的时候不需要传递token
在这里插入图片描述
直接上代码吧:

1.html代码

login2(this.user.id, this.ruleForm.tenantType)
.then(this.afterLogin)
.finally(() => {
    
    
  this.confirmLoading = false;
  if (this.ruleForm.tenantType) {
    
    
    localStorage.setItem('tenant', this.ruleForm.tenantType);
    let tenantUserName = '';
    let obj = this.tenantList.find(
      (item) => item.id == this.ruleForm.tenantType
    );
    if (obj) {
    
    
      tenantUserName = obj.name;
      localStorage.setItem('tenantUserName', tenantUserName);
    }
  } else {
    
    
    localStorage.removeItem('tenant');
    localStorage.removeItem('tenantUserName');
  }
});
afterLogin(res) {
    
    
  const loginRes = res;
  if (loginRes) {
    
    
    setAuthorization({
    
    
      token: loginRes.access_token,
      expireAt: new Date(new Date().getTime() + loginRes.expires_in),
    });
    if (checkAuthorization()) {
    
    
      this.$store.dispatch('account/refreshPermissions', (res) => {
    
    
        if (res == 'success') {
    
    
          this.$message.success('操作成功', 3);
          this.visible = false;
          this.confirmLoading = false;
          location.reload();
        }
      });
    }
  }
},

2.login2接口内容

export async function login2(id, tenant) {
    
    
  const params = {
    
    
    id
  };
  let config = {
    
    
    headers: {
    
    
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: '',//此处设置了请求token,但是并未生效
    },
  };
  if (tenant) {
    
    
    config.headers.__tenant = tenant;//设置请求头
  }
  return request(LOGIN, METHOD.POST, qs.stringify(params), config);
}

3.axios拦截器处理内容

const reqCommon = {
    
    
  /**
   * 发送请求之前做些什么
   * @param config axios config
   * @param options 应用配置 包含: {router, i18n, store, message}
   * @returns {*}
   */
  onFulfilled(config, options) {
    
    
    const {
    
     router, message } = options;
    const {
    
     url, xsrfCookieName, headers } = config;
    if (
      headers.Authorization &&
      xsrfCookieName &&
      !Cookie.get(xsrfCookieName)
    ) {
    
    
      message.warning('认证 token 已过期,请重新登录');
    }
    if (!headers.__tenant) {
    
    //如果有租户的信息,则表示要清空token,然后重新登录
      config.headers['Authorization'] = Cookie.get(xsrfHeaderName);
    } else {
    
    
      delete config.headers.Authorization;
    }
    return config;
  },
  //其他内容省略了。。。
}

完成!!!多多积累,多多收获!

猜你喜欢

转载自blog.csdn.net/yehaocheng520/article/details/131597906