[英]Error handling with POST signals from axios to Django Rest Server
我使用 React + Django,當用戶從前端注冊時,React 中的 axios 向 Django 發送 POST 信號,如果表單無效,則顯示下面的響應
xhr.js:178 POST http://localhost:8000/account/users/
signup.js:120 Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
如果我在 Django 可瀏覽的 API 或 Postman 中使用無效字段執行相同的 POST,我得到以下錯誤,向用戶顯示錯誤很有用
{
"email": [
"This field may not be blank."
],
"username": [
"This field may not be blank."
]
}
如果用戶在表單中和提交表單后輸入無效的詳細信息,如何從 axios 獲得相同的錯誤消息?
請注意,如果用戶在表單中輸入正確的信息,axios 會以足夠的詳細信息進行響應。
Axios function
axios.post('/account/users/',{data}).then(res=>console.log(res)).catch(err=>console.log(err)
不用說,兩種情況下的響應完全相同,即狀態為 400(錯誤請求)的 HTTP 響應和您在 postman 中看到的正文。 您的問題與 Axios 如何為您提供響應有關。 如果您想在 Axios 收到錯誤響應時訪問響應正文,您可以在error.response.data
中找到它:
axios.post('/account/users/'{data})
.then(res=>console.log(res))
.catch(err=>console.log('Response body', err.response.data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.