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

Adding the p5.js library to Stackblitz IDE: A step-by-step guide

Recently, I've been using Stackblitz as my IDE to improve my coding skills on my Chromebook. While it has been effective in many ways, I have encountered difficulties when trying to integrate the p5 library. As a beginner in programming, I only grasp ...

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

Troubleshooting issues with environment variables in Next.js version 12.2.2

I tried following the steps outlined in the official documentation, but I'm encountering an issue. Here is what I did: next.config.js const nextConfig = { reactStrictMode: true, swcMinify: true, env : { MORALIS_ID: 'moralisId', ...

What is the best way to retrieve information from an Array within a JSON Object?

I currently have a Json object called FriendJson, which contains an array field named friends. This is the Json Object: [ { "id": 4, "updated": "2023-01-07T22:06:23.929206Z", "created": "2023-01-0 ...

Tips for adding an svg element to an existing svg using d3.js

Can another SVG be appended to an existing SVG parent using d3.js? I have tried using the 'svg:image' attribute, but unfortunately, I lose full control over the inner SVG child. The DOM node is created by d3, but it is not rendered, resulting i ...

Using JavaScript to modify the text of a label seems to be a challenging

UPDATE: After carefully reviewing my code once again, I have identified the issue. The problem lies in the positioning of a certain function (unfortunately not included here), but rest assured that I have rectified it! Allow me to provide a brief summary ...

Why isn't my function being triggered by the Click event?

I can't figure out why the click event isn't triggering the btn() function. function btn() { var radio = document.getElementsByTagName("input"); for (var i = 0; i > radio.length; i++){ if (radio[i].checked){ alert(radio[i].value); } ...

Maintain only specific elements in jQuery by filtering out the rest

Here is a scenario with a page layout to consider: <div id="page-container" class=""> <div id="scroller"> <!-- This page should be removed --> <div id="page_1" class="pagina"></div> <!-- These pages should be kept --&g ...

Automatically populate input field after selecting from dropdown menu [ Laravel, Vue.js ]

Does anyone know how to create a feature in Vuetify that allows searching in the Product table and based on the selection from a dropdown, display data in an order table like shown in the picture below? If you have any hints or suggestions, please let me ...

Using jQuery Ajax to send data and retrieve responses in the Codeigniter framework

I am struggling with passing values in CodeIgniter and I need some guidance. Could you provide an example code snippet using CodeIgniter to send a value from a view to a controller using Ajax and jQuery, and then display the result on the same page? In my ...

When a base html tag is dynamically added, the browser mistakenly loads assets twice

When managing relative paths on a website, I utilize the <base> tag within the <head> section of each page. Although all resources loaded via relative-like paths in the documents are displayed correctly, my observations show that browsers such ...

How can function expressions result in a returned value?

Function expressions result in a value, unlike function declarations which do not. This distinction was clarified for me by others in a different SO thread (link provided). All functions default to returning undefined, hence the emphasis on "expression" ...

What is the process for implementing JavaScript in Django?

I'm a newcomer to this and although I've tried searching on Google, I haven't found a solution. I'm facing an issue where I can include JavaScript within the HTML file, but it doesn't work when I try to separate it into its own fil ...

Ajax received a response from http 409 and is now parsing it

Hey there! I've been working on parsing out the message object using Ajax, and I'm having a bit of trouble getting a reference to messages.msg. It's strange because it displays perfectly fine in Postman, but for some reason, I can't see ...

Modifying the title of a tab in Chrome with Vue: A step-by-step

What is the process for customizing the tab title of a Vue.js application from "Webpack App"? ...

Pressing the "Enter" key will submit the contents of

Hello, I have recently created a new chat box and everything seems to be working fine. However, I am facing an issue with submitting a message when I press enter (to go to the function Kucaj()). Can anyone provide assistance with this problem? I tried ad ...

Tips for properly panning across the canvas

I added event listeners to capture mouse movement, clicks, and releases in my code. canvas.addEventListener('mousemove', onMouseMove, false); canvas.addEventListener('mousedown', onMouseDown,false); canvas.addEventListener('mouseu ...

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

Maximizing Jest's potential with multiple presets in a single configuration file/setup

Currently, the project I am working on has Jest configured and testing is functioning correctly. Here is a glimpse of the existing jest.config.js file; const ignores = [...]; const coverageIgnores = [...]; module.exports = { roots: ['<rootDir&g ...