Utilizing Axios for transmitting an authentication token to the server

I'm just starting out with this project

Currently, I am developing a Vue application that connects to a WordPress backend and requires user login. To achieve this, I have implemented the Simple JWT-Login plugin. I've successfully managed to send the email and password to the backend and retrieve the JSON Web Token (JWT). However, when attempting to log in by sending the JWT back to the backend, I encounter an error message stating "Bad Request." Below is the function responsible for handling the login process:

    async login(){
      try{
        const response = await axios.post('/?rest_route=/simple-jwt-login/v1/auth&email=email&password=password', 
          {
            email: this.email,
            password: this.password,
          }
        );
        const token = response.data.data.jwt
        localStorage.setItem('token', token)
        console.log(token)
        const login = await axios.get(`/?rest_route=/simple-jwt-login/v1/autologin&JWT=${token}`)
        console.log(login)
        // this.$router.push("/");
      } catch(err){
        console.log(err)
        // if(err.response.status === 400){
        //   this.error = "Wrong credentials! Please make sure"
        // }
      } finally{
          
      }
    }

Answer №1

The problem stemmed from a configuration option within the plugin that was not clearly outlined in the documentation. For non-experts, the only way to discover this is through trial and error.

Specifically, the setting under "general" for SESSION needs to be enabled. https://i.stack.imgur.com/fP80M.png

Answer №2

After reviewing the documentation for Logging in Users, it appears that you simply need to include the previous token value as the JWT query parameter.

I have always found it more effective to utilize the params option in Axios for handling query parameters.

const login = await axios.get("/", {
  params: {
    rest_route: "/simple-jwt-login/v1/autologin",
    JWT: token,
  }
})

The issue you encountered was due to the fact that in this string...

'/?rest_route=/simple-jwt-login/v1/autologin&JWT=token'

The variable token needed to be interpolated; you were essentially sending "token".


You should apply a similar approach to your initial request. The email and password should not be included in the query string for this particular request.

axios.post("/", {
  email: this.email,
  password: this.password,
}, {
  params: {
    rest_route: "/simple-jwt-login/v1/auth",
  }
})

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 entire DOM refreshes when a user updates the input field

In my React component, I am managing two states: inputText and students. The inputText state tracks the value of an input field, while the students state is an array used to populate a list of student names. The issue arises when the inputText state change ...

How to use a filtering select dropdown in React to easily sort and search options?

Recently, I started learning React and created a basic app that utilizes a countries API. The app is able to show all the countries and has a search input for filtering. Now, I want to enhance it by adding a select dropdown menu to filter countries by reg ...

Utilizing ReactStrap: a guide to retrieving the id of the chosen dropDownItem

In my code, I have a dropdownList component with various DropdownItems: <Dropdown isOpen={this.state.dropdownOpen[3]} toggle={() => { this.toggle(3); }} > <DropdownToggle className="my-dropdown" car ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Issue with Empty Date Time Format in Vue2 Date-Picker

In our company, we use vue2-datepicker to manage the starting and ending times of meetings. The dates are stored in "YYYY-MM-DD HH:mm" format on the backend, but we convert them to "DD-MM-YYYY HH:mm" format when retrieving the data in the mounted() hook. T ...

Tips on removing authentication token when logging out in react native

Working with the Django Rest Framework and React Native for the front-end, I am currently facing an issue where the authentication token persists even after a user logs out from the front-end. This is evident as the token still shows in the Django admin pa ...

IE is failing to display the textarea, but it is successfully getting submitted

I've written a function in jQuery and JavaScript that generates a form element: createEmail: function(title){ var $emailForm = $('<form>',{action: 'sendEmail.php', id: 'emailForm'}); var $table = $( ...

Using Vue 3 to send formdata with axios

I've been attempting to upload images to a backend expressjs API using Vue 3. I'm creating a FormData object named "files" and sending it via axios to the server. However, the server isn't receiving anything (req.files is undefined). The ser ...

I have managed to update the Immutable and Primitive Data-Types in JS. Now, the question arises - are these truly Primitives or are the concepts in

In JavaScript, there are 4 primitive data types that store values directly: String, Number, Boolean, and Symbol. I am excluding undefined and null from this list as they are special data types with unique characteristics. One key feature of primitives is ...

Selenium, scrolling through web pages

I have been attempting to scroll through a webpage using Selenium at "https://jobsearch.az/vacancies". However, when you open the page and click on a job vacancy, there are two side-by-side pages that need to be scrolled. The challenge is to scroll the one ...

Arrange a set of items using AngularJS according to specific criteria

Hello, I'm new to Angular I've created an angular app and you can view it in this plunkr. Can someone guide me on how to sort the list displayed here using angular? I want the course with the flag to always stay on top, while sorting the rest o ...

Check if a specific string is present in an array using JavaScript

When working with SQL, we can easily check if a string is in a list using the following syntax: Column IN ('a', 'b', 'c') But how can we achieve this in JavaScript without it being so cumbersome? if (expression1 || expressi ...

What is a way to utilize Javascript in order to copy a JSON object by referencing a specific key within the object?

If you had the following JSON object example given, how could you utilize Javascript to replicate each object based on the value indicated in the "Count" key? Example Input: [ { "name":"David", "Count":2 }, { "name":"John", "Count":3 }, ] Desired Out ...

What is the process for utilizing SWR to display information from a GraphQL Apollo Server within a NextJS application?

While I can successfully access my GraphQL query using apollo-graphql-studio, and the resolver is configured correctly, I am facing difficulty in rendering the data. Being aware of the performance benefits of swr react-hook in next-js, I intend to fetch d ...

Creating a Vue.js component that animates text to fade in and out within a textarea when a button

I need assistance with updating a <textarea> element in my Vue application. Currently, I have the textarea bound to some data in my state. However, when a button is clicked, I want the existing data in the textarea to fade out and be replaced with ne ...

Move the material ui menu to the far left side of the page

How can I adjust the menu to align with the left side of the page without any gaps? I've tried various methods but it's not moving to the left. Any suggestions? Here is the relevant code snippet: <Menu an ...

What is the best method for including parameters in OBJECT_URL when sharing a post on Facebook?

Regarding this line: FB.api('/me/namespace:read' + '?article=http://www.xxxxxxxxxxxxxx/tm/redir.php&access_token=','post', Whenever I attempt: I encounter errors. How can I successfully pass parameters in the OBJECT_UR ...

Filter an array of objects based on a provided array

I have an array of objects that I need to filter based on their statuses. const data = [ { id:1, name:"data1", status: { open:1, closed:1, hold:0, block:1 } }, { id:2, name:"data2", ...

Obtaining the ID from a URL in node.js

As a newcomer to the world of Javascript and node.js, I am venturing into creating a REST API with URLs structured as follows: /user/{userId}/docs The goal is to extract the value of {userId}, which, for instance, in the URL /user/5/docs would be 5. Wh ...

script loop causing an embedded form

While trying to include a Hubspot embedded form on a page using a script, I encountered an issue. I utilized onMounted to ensure the form is displayed correctly. However, upon leaving and re-entering the component where the form is located, an additional b ...