Extract token from the URL and then use Axios in Vue.js to send it to the POST API

Hey there, I'm in need of extracting a token from the URL

http://192.168.178.25:8080/register?token=eyJhbGciOiJIUzI...

and then making a POST request to the API to confirm the account.
I've attempted this but encountered a SyntaxError on the backend!
Can anyone lend a hand?

<script>
import axios from 'axios'
export default {
    name: 'Register',
    data() {
        return {
            confirmation : false,
            somethingWrong: false       
        }
    },
    
    created: function() {
        axios.post('/api/users/validateRegister', null,{
            params: {
                registerToken: this.$route.query.token,
                state: this.$route.query.state
            }
        })
        .then((res) => {
            console.log(res)
            this.confirmation = true       
        })
        .catch((err) => {
            console.log(err)
            this.somethingWrong = true
        })
    }
}
</script>

Answer №1

Your server is anticipating JSON data, but you are sending something different.

Try executing this in your browser console (devtools): JSON.parse('asdasd').

The way you are currently sending the request:

axios.post('/api/users/validateRegister', null,{
  params: {
    registerToken: this.$route.query.token,
    state: this.$route.query.state
  }
})

Will result in a request that appears like this:

/api/users/validateRegister?registerToken=<token>&state=<state>

To make a POST request with data body as per the documentation, use this syntax:

axios.post(url[, data[, config]])

In your scenario, for including registerToken and state in the body rather than query parameters, do it like this:

axios.post('/api/users/validateRegister',{
  registerToken: this.$route.query.token,
  state: this.$route.query.state
})

Observe there is no null in the 2nd parameter and no params: {}


According to the documentation, you can also use this alternate syntax:

axios({
  method: 'post'
  url: '/api/users/validateRegister',
  data: {
    registerToken: this.$route.query.token,
    state: this.$route.query.state
  }
})

Answer №2

It appears that your server is encountering an issue while attempting to process the body.

Upon inspecting your axios request, it seems that you are passing parameters instead of a body - this can be observed by examining the URL in the POST error displayed on the right side of your screenshot.

To resolve this, ensure that you send the payload in the body as shown below:

axios.post('/api/users/validateRegister', 
   {
      registerToken: this.$route.query.token,
      state: this.$route.query.state
   })

Since there is no server-side code provided, there may be other underlying issues that are not immediately visible to us.

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

Deselect the checkbox that has been selected using a JavaScript function

I have been searching everywhere for a solution and I am hoping someone in this community can assist me. I am working with a script that triggers when a checkbox is selected from a group of checkboxes. Each checkbox is given a value of "customer id". < ...

Nothing remains after the fall: coding void

I am facing an issue where my item becomes null after being dragged 2-3 times and dropped in a different place. I have included my code below and I can't seem to figure out where the mistake lies. Can you please review it and let me know what needs to ...

Is there a way to ensure the content of two divs remains aligned despite changing data within them?

Currently, I have two separate Divs - one displaying temperature data and the other showing humidity levels. <div class="weatherwrap"> <div class="tempwrap" title="Current Temperature"> ...

A guide to toggling the check/uncheck status of a list box by clicking on a checkbox using

I am using a div and CSS id to control the checkbox check and uncheck functionality, but I am not getting the desired outcome from my source code Step 1: By default, the checkbox is unchecked and the listbox is disabled Step 2: When the checkbox is check ...

Create a basic Vue.js page using Flask as a single server

There are numerous examples on the internet showcasing applications built with Flask (API) and Vue.js (client). Since Vue is a single-page application (SPA), it makes sense to serve it with Flask as well. However, I have encountered difficulties in finding ...

The Discord OAuth2 bot fails to assign roles to authenticated users

While working on OAuth2 login for my website, I encountered an issue. After a user successfully logs in through OAuth2, the bot should assign a role to them on my Discord server. However, when I tested the login process myself, the bot returned an error me ...

Gatsby is throwing an error because the location props are not defined

I am attempting to utilize location props in my Gatsby page. In pages/index.js, I am passing props within my Link: <Link state={{eventID: event.id}} to={`/date/${event.name}`}> </Link> In pages/date/[dateId]/index.js: const DateWithId = ( ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...

Is there a way for me to showcase a collection of pictures in an array format

I am facing an issue on my react page where the data is successfully fetched from an API, but I am having trouble fetching the array of images. Below is the code snippet that I have written: import React, {Component} from 'react'; export defaul ...

Issue with pushing inner list<object> in Knockout version 3.2.0

Currently, I am working with knockout.js on an ASP application. The issue I am facing involves a list of objects returned by the controller action to the view, where the objects in the list point to another list of objects. My struggle lies in adding new o ...

When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on: <script type="text/javascript"> functi ...

Broaden the reach of the ajax .done function to encompass the surrounding function

It seems like my previous attempts to find a solution for the function below were unsuccessful: function countNoFilters(keyword){ keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#keyword-hidden").val(); var getR ...

Error: The variable "Tankvalue" has not been declared

Is there a way to fix the error message I am receiving when trying to display response data in charts? The Tankvalue variable seems to be out of scope, resulting in an "undefined" error. The error message states that Tankvalue is not defined. I need to ...

What is the reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

How can I stretch a background image using jquery to cover the entire document instead of just the window

I have implemented a plugin called https://github.com/srobbin/jquery-backstretch to effectively stretch the background image. The problem arises when the content of the page is long enough to create a scrollbar. In this case, while scrolling, the backgrou ...

The Vuex state is being modified by an action, yet the associated computed property fails to react accordingly

I am facing an issue with fetching data from firebase using a store.js file that I have imported into the main.js. The problem is that the data does not display correctly when the page loads. However, when I check the console.log in mutations, it shows t ...

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

"Unraveling Vue.js: A guide to fetching JSON data one object at a time

I am facing a challenge with a large JSON file (40 MB) that includes data on countries, their IDs, and a total sum that I need to calculate. { "0": { "id": 0, "country": "usa", "sum": 201, }, ...

Using jQuery to enhance the functionality of the drop-down select feature

I am facing an issue with my index file code. When I select something from the drop-down menu, I expect to see a related dropdown appear. Although I have added this code to my file, I am unable to get the drop down to show after selecting the main type. ...