Search code examples
javascriptnode.jsvue.jsjwtexpress-jwt

How can I access ["x-access-token"] in Vue.js front end?


I have an application that uses ["x-access-token"] as token in the header, when I try to access the token in the header I keep gettting "no token provided". I use jwt for authentication

This is how I'm accessing it in the script tag:

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

this is my authorization middleware for verifying tokens in the browser, my header uses "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"
    });
  }
};

and my authenticated route to get the current logged in user

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

When I check my local storage I see the token but can't seem to understand why I keep getting no token provided when trying to get the user in my front end


Solution

  • try

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