Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

507
Views
how to access bearer token in vue

I'm trying to get the current user info using jwt token after successfully login, the token is saved in the browser but each time i send the request i get an error

token i get in my application tab on my console

token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MjM4NzA4ZDc2ZDVkMDJmZWMwNGRiZDEiLCJpYXQiOjE2NDgwODI3MTV9.xvFdGR8skZntTIdlo9aSCx90315rSoUxct_VIR9cf6Q

error i get in my console when i'm on the user route

{
    "success": false,
    "message": "Failed to authenticate"
}

my script tag to get the current user info


<script>
import axios from "axios";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App"
    };
  },
  mounted() {
    axios
      .get("http://localhost:5000/api/auth/user", {
        headers: {
          Authorization: "Bearer ${token}",
          token: localStorage.getItem("token")
        }
      })
      .then(res => {
        console.log(res);
      });
  }
};
</script>

backend route for authentication

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

jwt middleware to verify the 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) {
        console.log(err)
        res.json({
          success: false,
          message: "Failed to authenticate"
        });
      } else {
        req.decoded = decoded;

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

i dont get why i'm getting an error when my token is saved in my local storage

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you should see your token in console.

if you dont see, you did not save correctly. you must check your save method.

<script>
import axios from "axios";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App"
    };
  },
  mounted() {
    let token=localStorage.getItem("token");
   console.log(token);
    axios
      .get("http://localhost:5000/api/auth/user", {
        headers: {
          Authorization: `Bearer ${token}`,
          token: token
        }
      })
      .then(res => {
        console.log(res);
      });
  }
};
</script>

and i arranged your middleware method. for get token, you can split space charecter and take last index.

const autheticateToken = (req, res, next) => {
    var authHeader = req.headers.authorization;
    const token = authHeader?.split(' ')[1];
    if (token === null) {
        return res.json({
          success: false,
          message: "Failed to authenticate"
        });

    }
    JWT.verify(token, process.env.SECRET, (err, decoded) => {
        if (err) {
            return  res.json({
          success: false,
          message: "Failed to authenticate"
        });
        }
        req.decoded = decoded;
        next();
    });
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!