Vue中如何向用户显示axois post请求

How to display to the user axois post request in Vue

我想向用户显示从 axois post 请求收到的消息,以防他在注册时输入错误的数据。

输入无效数据时,我收到错误代码 400,响应是 json 对象,其中包含 The password is too similar to the username.

等错误

我尝试 return 我的 catch 块中的数据,但这没有用,我试图在 vuex 中创建一个状态变量并将响应分配给它,但这也没有用。

我如何才能获得对我的组件的响应,以便我可以将其显示给用户?

Vuex 动作

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

错误消息“密码与用户名太相似。”应该在您收到的回复正文中,以便您可以使用

访问它
catch (err => console.log(err.response.data);

我仅限于根据所提供代码的解释来解决问题

错误:

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

然后要求在突变中声明它

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

终于在这里总结状态

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

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

希望有用