[英]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.