Home > Software engineering >  How to display to the user axois post request in Vue
How to display to the user axois post request in Vue

Time:04-27

I would like to display to the user the message received from axois post request in case he entered wrong data when signing up.

When entering not valid data, I get a error code 400 with a response which is a json object which contains the error such as The password is too similar to the username.

I tried to return the data in my catch block but that did not work, and I tried to create a state variable in vuex and assign to it the response but that did not work as well.

How can I get that response, to my component, so that I can display it to the user?

Vuex action

async SignUp({ commit }, { username, password }) {
        const response = await axios.post('...', {
///the is to ... hide the server url :)
            username: username,
            password: password
        })
            .catch(error => {
                console.log(error)
                
                ///state.registerError = error.response //this is did not work
                ///return error.response //this is did not work
            })
        commit('setUser', response.data)
    }

CodePudding user response:

I limit myself only to solving the problem based on the interpretation of the code provided

Error:

state.registerError = error.response //this is did not work // you cannot change state directly, for this you can/has to use MUTATIONS. Changed:

commit("setErrorHttp", error) // Error captured from axios

async SignUp({ commit }, { username, password }) {
    const response = await axios.post('...', {
        username: username,
        password: password
    })
        .catch(error => {
            console.log(error)
            commit("setErrorHttp", error) // Error captured from axios
        })
    commit('setUser', response.data)
}

Then require declare it the in mutations

setErrorHttp // The handler function is where we perform actual state modifications. You can consulting doc https://vuex.vuejs.org/guide/mutations.html. The solution:

setErrorHttp: (state, payload) => {
    state.registerError = payload // TODO: feel free to customize your response to the user, contained in payload.
}

Finally here conclusion with state

So registerError could be used from any component (e.g ShowErrorHttp.vue); Through mapGetters, mapState or if you prefer with $state.registerError.

state: {
  registerError : null // or make Object customized relationships with Component
}

I hope it will be useful

CodePudding user response:

the error message "The password is too similar to the username." should be in the body of the response you received so you can access it with

catch (err => console.log(err.response.data);
  • Related