vue.jsaxiosxmlhttprequestx-www-form-urlencoded

Duplicated params on second login when sending urlencoded data via Axios


I'm doing token based authentication and I have to send urlencoded data via axios. The user and the password are passed to the axios function and I passed all the parameters according to the documentation.

import axios from 'axios'

const params = new URLSearchParams()
params.append('client_id', 'xyz-client')
params.append('secret', 'xyz')
params.append('scope', 'xyz')
params.append('grant_type', 'password')

const config = {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: 'Basic zyx=',
    },
}

export default {
    authUser(userData) {
        params.append('username', userData.email)
        params.append('password', userData.password)
        return axios.post(
            'myhttpAPI',
            params,
            config
        )
    },
}

Everything is totally fine when the user logins for the first time BUT if I logout of the application and then try to login again the post request fail. I realized that on that second login request the axios call for some reason is duplicating the params added within the authUser function, so on the first login the payload is this:

client_id: xyz
secret: xyz
scope: xyz
grant_type: password
username: xyz
password: xyz

And if I logout and then try to login again (without reloading the page) the payload is this:

client_id: xyz
secret: xyz
scope: xyz
grant_type: password
username: xyz
password: xyz
username: xyz
password: xyz

As you can see the username and the password parameters are repeated so the API gives me this error:

{"error":"invalid_request","error_description":"Could not find agent with username bond@test.com,bond@test.com"}

Because the axios request is duplicating those parameters. I don't really know if this is a backend bug or If the axios post is not well formed. I also realized that if I reload the page everything works fine, so the problem is while I'm trying to login again without reloading the page.


Solution

  • According to MDN if you use 'set' it will replace any existing values of the same name. This should solve your problem as you appear to be appending the additional values.

    https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/set