我想向用戶顯示從 axois 發布請求收到的訊息,以防他在注冊時輸入了錯誤的資料。
輸入無效資料時,我收到一個錯誤代碼 400,其回應是一個包含錯誤的 json 物件,例如The password is too similar to the username.
我試圖在我的 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)
}
uj5u.com熱心網友回復:
我僅限于根據對提供的代碼的解釋來解決問題
錯誤:
state.registerError = error.response //這不起作用// 你不能直接改變狀態,為此你可以/必須使用 MUTATIONS。改變:
commit("setErrorHttp", error) // 從 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 // 處理函式是我們執行實際狀態修改的地方。您可以咨詢檔案 https://vuex.vuejs.org/guide/mutations.html。解決方案:
setErrorHttp: (state, payload) => {
state.registerError = payload // TODO: feel free to customize your response to the user, contained in payload.
}
最后在這里總結與狀態
所以registerError可以從任何組件中使用(例如 ShowErrorHttp.vue);通過 mapGetters、mapState 或者如果您更喜歡 $store.state.registerError。
state: {
registerError : null // or make Object customized relationships with Component
}
我希望它會有用
uj5u.com熱心網友回復:
錯誤訊息“密碼與用戶名太相似”。應該在您收到的回應的正文中,以便您可以訪問它
catch (err => console.log(err.response.data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466018.html
