methods to retrieve bearer token in Vue application

After successfully logging in, I am attempting to retrieve the current user information using a JWT token. Despite saving the token in the browser, I encounter an error every time I send the request.

I can locate the token in my application tab on the console as follows:

token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MjM4NzA4ZDc2ZDVkMDJmZWMwNGRiZDEiLCJpYXQiOjE2NDgwODI3MTV9.xvFdGR8skZntTIdlo9aSCx90315rSoUxct_VIR9cf6Q

The error message displayed in my console when accessing the user route is:

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

This is the script tag used to retrieve the current user information:


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

The backend route for authentication is as follows:

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

The JWT middleware used to verify the token is shown below:

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'm baffled by why I keep receiving an error despite having the token saved in local storage.

Answer №1

Make sure to check the console for your token when running this code.

If you can't see it, double-check your save method as it may not have been saved correctly.

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

I've also organized your middleware method for getting the token. To retrieve the token, split the string by space character and take the last index.

const authenticateToken = (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();
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The effects of external CSS are not being displayed or are being overridden

I am currently working on a webpage design that resembles the style of Microsoft's website. I came across a tutorial on W3 Schools for creating an image slideshow, which can be found here: https://www.w3schools.com/howto/howto_js_slideshow.asp. The ex ...

Zone.js error: Promise rejection caught

When I call a function from an external library on page load in my Angular application, Chrome dev tools console shows the error message: "Unhandled Promise rejection: Cannot read properties of undefined (reading 'page') ' Zone: <root> ...

What is the best way to export a React Material-UI component with two separate styles objects in Material-UI V1?

We are currently utilizing material-ui version 1 and composing Higher Order Components (HOC) with the recompose utility. Our issue arises from having two separate styles objects - one defined within the component itself, and another general style object th ...

What steps can be taken to avoid being logged out automatically upon clicking the back button?

Currently, my code automatically logs out of the application when the browser is closed. However, I am facing an issue where it also logs out when I press the browser's back button and navigate to another page. I would like the code to only logout au ...

What methods can be used to verify the accuracy of an Oracle query?

Greetings Tech Enthusiasts, Currently, I am working on a .net application using C# that will provide users with a front end to write queries and view the results in a gridview table. I am facing a challenge in validating an Oracle query/syn ...

How to implement various conditional classes in Vue.js

When working with Vue, I utilized style binding in the following manner: v-bind:style="{'width': + width + 'px', 'left': + x + 'px', 'top': y + 'px'}" However, when attempting to bind multiple c ...

Adjust the size of the text editor in eXtplorer's EditArea module

Looking for guidance on adjusting the height of the text editor (EditArea) within eXtplorer. Any assistance would be greatly appreciated! ...

Glistening: sending reactiveValues to conditionalPanel

Is it possible to pass a reactiveValues to the condition of a conditionalPanel? If so, what is the correct method? Below is my attempt in the UI.R file for the conditionalPanel: conditionalPanel(condition = "values.cond == 0", etc. I have defined values ...

Experiencing difficulties integrating relational data with Angular and MongoDB

I have a view where I display 'Transporters'. Each Transporter has multiple 'Deliveries', so I want to associate Deliveries with the corresponding Transporters. My tech stack includes express, mongoose, and angular.js. Here are my mode ...

Getting Started with Angular JS: A Beginner's Essentials

I am feeling lost on where to begin with developing my app. When I click the add button, I want a form to show up - should I append a div to that button? How should I approach this problem? Snippet of Code: <body> <div id="wrap"> <!- ...

Utilizing jQuery to Refine an Array

I am currently working on implementing a feature to filter an array based on user input of a city. While I have successfully populated the drop-down menu, I am encountering an issue with the search bar functionality. The goal is to filter the array list ac ...

AJAX request function is only successful on the first attempt

Currently, I am implementing AJAX functionality to verify whether a user-input ID exists in the database. If the ID is found, a check mark is displayed; if not, a cross mark is displayed. The issue arises when I input an ID for the first time, which is pr ...

Having trouble utilizing a function with an async onload method within a service in Angular - why does the same function work flawlessly in a component?

I successfully created a component in Angular that can import an Excel file, convert it into an array, and display its content as a table on the page. The current implementation within the component looks like this: data-import.compoent.ts import { Compo ...

Uploading files in NodeJS using the multer library

I am attempting to upload a file to a specific directory on the disk using the multer library. As I analyze the code, it seems that when a request is made, the file is taken from it and saved separately from the rest of the request. Is there a way to acces ...

A guide on transferring data between two arrays of objects using TypeScript

I am working on implementing a get request within a component that retrieves a response: getPaymentIntents(): Observable<Payment>{ const url: string = 'https://store.com//payments'; return this.http.get<Payment>(url); } ...

Prohibit the utilization of application/json in a single request

Below is the code I have written to send a request for uploading a file: const uploadReq = new HttpRequest('POST', "https://localhost:44372/api/v1/Upload/UploadNewsPic" , formData, { reportProgress: true }); this.http.request(uploadReq).sub ...

Javascript encounters an unforeseen < token

I encountered an unexpected token < error in my JavaScript file. Despite checking the code using JSHint, I couldn't find any issues that could resolve the problem. I attempted to place the JavaScript code in a separate file and also tried embeddin ...

What could be causing the malfunction of the Facebook iframe like button?

Even though it functions offline, there seems to be an issue with its performance online. Here is the code that was used: <iframe src="http://www.facebook.com/plugins/like.php?app_id=125925834166578&amp;href=http%3A%2F%2Fwww.facebook.com%2FBaradei. ...

Transferring my JavaScript variable to PHP through Ajax

I'm currently facing an issue where my JavaScript variable is not being successfully passed to a PHP variable using AJAX in order to update my SQL database. The function is being called, but for some reason the data is not being sent to PHP.php. UPDA ...

Developing a personalized child node on Firebase's real-time database using React Native

Seeking assistance as a newcomer to Firebase and React, I've exhausted all my options and appreciate any help you can provide. Here is the data structure I am using in Firebase: https://i.sstatic.net/fKtdK.png When adding a new Beverage type, such ...