如何在vue js前端访问["x-access-token"]

how to access ["x-access-token"] in vue js front end

你好,我有一个应用程序在 header 中使用 ["x-access-token"] 作为令牌,当我尝试访问 header 中的令牌时,我一直在尝试“未提供令牌”,我使用 jwt 进行身份验证

我的控制台出现错误 https://imagizer.imageshack.com/img924/4851/2uF6qj.jpg

这就是我在脚本标签中访问它的方式


<script>

import axios from "axios";

export default {

  data() {
    return {
    
      name: "",
      email: "",
     
    };
  },
  created() {
    //user is not authorized
      if (localStorage.getItem("token") === null) {
      this.$router.push("/login");
    }
  },
  
  mounted() {
     axios
      .get("http://localhost:5000/api/auth/user", {
        headers: {
          Authorization:'Bearer' + token,
          token: localStorage.getItem("token") }
      })
      .then(res => {
        console.log(res)
        this.name = res.data.foundUser.name;
        this.email = res.data.foundUser.email;
      });
  },

 
};
</script>

这是我用于在浏览器中验证令牌的 auth 中间件,我的 header 使用“x-access-token”

const jwt = require("jsonwebtoken");

module.exports = function (req, res, next) {
  let token = req.headers["x-access-token"] || req.headers["authorization"];
  let checkBearer = "Bearer ";

  if (token) {
    if (token.startsWith(checkBearer)) {
      token = token.slice(checkBearer.length, token.length);
    }

    jwt.verify(token, process.env.SECRET, (err, decoded) => {
      if (err) {
        res.json({
          success: false,
          message: "Failed to authenticate"
        });
      } else {
        req.decoded = decoded;

        next();
      }
    });
  } else {
    res.json({
      success: false,
      message: "No token Provided"
    });
  }
};

和我的认证路由获取当前登录用户


// Get Profile
router.get("/auth/user", verifyToken, async (req, res) => {
    try {
      let foundUser = await User.findOne({
        _id: req.decoded._id
      }).populate(
        "address"
      );
      if (foundUser) {
        res.json({
          success: true,
          user: foundUser
        });
      }
    } catch (err) {
      res.status(500).json({
        success: false,
        message: err.message
      });
    }
  });

当我检查我的本地存储时,我看到了令牌 https://imagizer.imageshack.com/img923/6844/3MVokP.jpg 但似乎无法理解为什么我在尝试让用户进入我的前端时一直没有提供任何令牌

尝试

    const token = localStorage.getItem("token")

     axios
      .get("http://localhost:5000/api/auth/user", {
        headers: {
           Authorization:'Bearer ' + token,
          'x-access-token': token 
        }
      })