为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白猪掌柜的 2021-09-17 12:29:08
我正在尝试使用 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]我在我的 Django 后端使用Django REST 框架进行身份验证。使用 Insomnia 一切正常,但任何通过 React 的请求都会导致“错误请求”django-cors-headers 也已安装和配置。
查看完整描述

1 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

在这里回答我自己的问题。


设置解析器来JSONParser解决这个问题。


在项目范围内设置它是最好的选择 -


REST_FRAMEWORK = {

    'DEFAULT_PARSER_CLASSES': [

        'rest_framework.parsers.JSONParser',

    ]

}

从 Axios 发送请求时,还要将标头设置为 json。


headers: {

    'Content-Type': 'application/json'

}

谢谢你的帮助!


查看完整回答
反对 回复 2021-09-17
  • 1 回答
  • 0 关注
  • 207 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信