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

`There was an issue with an unfinished string literal.`

Currently, I am utilizing jQuery to display the information from a JSON string generated by PHP and extracted from a database. However, I have encountered an issue where some of the data spans multiple lines... How can I prevent this from triggering an un ...

Error: React Native Component Exception - a potential hiccup in

As a newcomer to React Native, I've encountered an issue while trying to bind data from a local JSON server API. Everything worked fine when I used a class component for my EventList, but after integrating Navigation in App.js and changing it to a fun ...

The Kenburn zoom image effect fails to function

I want to implement a zoom effect on an image using the Ken Burns effect when it is clicked. However, the code I have written does not seem to be working as expected. Here is the code snippet: $(document).ready(function () { $('.kenburns').on( ...

Is there a way to initiate multiple AJAX requests once a single request has been completed successfully?

I have created two functions and I want to call the get_name_from_id function when my first ajax function is successful. However, it is not working as expected. When I add an alert in the get_name_from_id function after the jsonString variable like alert ...

Jquery is not displaying the background color of the progress bar

Greetings to all! I am currently working on implementing a progress bar for my website, but I am encountering an issue where the background-color is not displaying correctly on scroll. I would greatly appreciate any assistance with this matter. Below you c ...

I'm having trouble getting my .click method to work with the <div id=menuButton>. Can anyone help me figure out why this is happening?

Here is the HTML code I created for a dropdown menu. Initially, in the CSS file, the menu is set to display: none; <!doctype html> <html> <head> <title>DropDown Menu</title> <link rel="stylesheet" href="normalize ...

Tips on passing a variable and API response to the following promise in JavaScript!

Using the initial promise "crypto.model.find()" allows me to store an array of "symbols" ( symbol[] ) from the database and retrieve some IDs that I will utilize to construct a URL for making a request to an API using axios.get(url). Upon receiving a resp ...

After declaring a useState variable in React, the code following it will not be executed

Currently, I am facing a peculiar problem with the useState hook in my React project. I have a custom hook called useAxios which relies on useState to handle state management. Strangely, any console.log commands placed after the useState declarations do no ...

Modifying the structure of serialized data

After serializing a JS form, the data looks like this: .....&xx=xxx&otherError=&input=SMS&message=sdfgs&...... Can anyone provide guidance on how to replace the value of message with the content of a textarea before making an ajax cal ...

verifying the presence of a string or value within an array

I'm currently working on a feature that involves adding an element to an array by typing something into a text field and clicking a button. I've also implemented an if statement to check if the input already exists in the table, and show an alert ...

Is it possible for a mobile web application to continue running even when the screen is

Thinking about creating a mobile web application with the use of jQuery Mobile for tracking truck deliveries. I'm interested in sending GPS coordinates back to the server periodically. Is this possible even when the screen is turned off? If not, any ...

Having trouble with the date format in the highCharts range selector?

I am encountering an issue while trying to implement the rangefilter feature with HighCharts. The start and end dates are appearing incorrect, indicating that my date is not being recognized properly. My x-axis consists of unique dates as categorical valu ...

HTML - Retain placeholder text while user inputs

My input is structured like this: <input value="My text" placeholder="Placeholder"> Typing in the input causes the placeholder text to disappear, which is expected. However, I am looking to keep the placeholder text visible as a background behind ...

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...

Leverage Vue's ability to assign data from a parent component to

I am struggling to bind the data (inputData) from the parent component to my child component. I have checked my code multiple times but cannot find where the mistake is. MainApp.js let vm = new Vue({ el: "#app", components: { &ap ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

Is there a proven method to instantly update local state in React/Redux without needing to wait for a response from an API call?

Summary: Are there any well-known solutions using React/Redux to achieve a fast and responsive UI, while seamlessly updating an API/database even in cases of failed requests? I want to develop an application featuring a "card view" functionality using htt ...

What is the best way to confirm checkbox selection based on MySQL data?

Writing this question feels challenging, but I have a collection of checkboxes with their data stored as JSON in my PHP database. What I'm trying to achieve now is to dynamically load the JSON data on the page without refreshing it, checking specific ...

Scrolling to specific ID scrolls only in a downward direction

I have been using fullpage.js for my website and I am facing an issue. When I create a link and connect it to an id, everything works perfectly. However, I am unable to scroll back up once I have scrolled down. Here is the HTML code: <a href="#section ...

Use the inline IF statement to adjust the icon class depending on the Flask variable

Is it feasible to achieve this using the inline if function? Alternatively, I could use JavaScript. While I've come across some similar posts here, the solutions provided were not exactly what I expected or were implemented in PHP. <i class="f ...