Dan
Dan

Reputation: 39

Get token from URL and send to post api with Axios Vuejs

Hi i need to take token from URL http://192.168.178.25:8080/register?token=eyJhbGciOiJIUzI...
and send a Post request on API for confermation account
I have tried this but on backend i've receive SyntaxError!
Someone can help me?

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

Upvotes: 1

Views: 1756

Answers (2)

captainskippah
captainskippah

Reputation: 1559

Your server is expecting JSON but you are sending something else.

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

How you are sending it right now:

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

Will send a request that looks like:

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

To do a POST request with body according to docs, you do:

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

Which in your case means, assuming you need registerToken and state as part of body and not query parameters:

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

Notice how there's no null in the 2nd param and no params: {}


You can also according to docs do the following syntax:

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

Upvotes: 1

paddyfields
paddyfields

Reputation: 1539

It looks like your server is throwing an error when trying to parse the body.

From your axios request, you're passing parameters instead of a body - you can see this by looking at the URL in the POST error on the right-hand side of your screenshot.

Instead, send the payload in the body like this;

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

As you haven't provided any of the server-side code there may be something else going on we can't see.

Upvotes: 0

Related Questions