[英]400 Bad Request from Axios to Django, field is required
我正在嘗試使用Axios從我的React前端發送POST請求
import axios from 'axios'
axios.post('http://server:port/auth/login', {
username: 'admin',
password: 'MY_PASSWORD',
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error.response)
});
無論我做什么,我都會收到一個400錯誤的請求,指出:
"username":[This field is required],
"password":[This field is required]
我在Django后端中使用Django REST框架進行身份驗證。
使用Insomnia一切都可以正常工作,但是任何通過React的請求都會導致“錯誤請求”
django-cors-headers也已安裝和配置。
在這里回答我自己的問題。
將解析器設置為JSONParser
解決此問題。
最好在整個項目范圍內進行設置-
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}
在從Axios發送請求時,還將標頭設置為json。
headers: {
'Content-Type': 'application/json'
}
謝謝誰的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.