我们在前端获取请求头中的数据,只能获取默认的几个请求头,若想获取自定义请求头,需要在后端服务器进行设置

Access-Control-Expose-Headers

后端代码:

 @GetMapping("checkCode")//校验邮箱登录的code
    public AxiosResult<?> checkCode(String email, String code,HttpServletResponse response) {
        ValueOperations<String, String> jedis = stringRedisTemplate.opsForValue();
        String realCode = jedis.get(email + "-Code");
        if (realCode != null && realCode.equals(code)) {
           stringRedisTemplate.delete(email + "-Code");
            //发放token
            Long userId = Long.parseLong(Objects.requireNonNull(jedis.get(email + "-Id")));
            String encodeToken = JwtUtil.encode(userId);
            response.addHeader("Authorization",encodeToken);
            response.setHeader("Access-Control-Expose-Headers","Authorization");
            logger.info("已成功向Id="+userId+"用户发放token");
            UserInfo userInfo = userService.viewById(userId);
            return AxiosResult.success(userInfo);
        } else {
            return AxiosResult.failed();
        }
    }

前端代码(Vue):

const loginBtnFun = () => {
  localStorage.setItem("blog_token","ceshitoken")
  axios.get("login/checkCode?" + qs.stringify(emailForm))
      .then(respData => {
        if (respData.data.status === 2001) {
          const token = respData.headers['authorization'];
          localStorage.setItem("blog_token",token)
          router.push("/main")
        }
        console.log(respData)
      })
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐