从 Axios 到 Django 的 400 错误请求,该字段是必需的

我正在尝试使用 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 Bad Request 响应,说明:


"username":[This field is required],

"password":[This field is required]

http://img1.mukewang.com/614419b30001fcab09400223.jpg

我在我的 Django 后端使用Django REST 框架进行身份验证。

使用 Insomnia 一切正常,但任何通过 React 的请求都会导致“错误请求”

http://img.mukewang.com/614419c00001919105610765.jpg

django-cors-headers 也已安装和配置。


白猪掌柜的
浏览 208回答 1
1回答

缥缈止盈

在这里回答我自己的问题。设置解析器来JSONParser解决这个问题。在项目范围内设置它是最好的选择 -REST_FRAMEWORK = {    'DEFAULT_PARSER_CLASSES': [        'rest_framework.parsers.JSONParser',    ]}从 Axios 发送请求时,还要将标头设置为 json。headers: {    'Content-Type': 'application/json'}谢谢你的帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript