gpt4 book ai didi

javascript - 从 Axios 到 Django 的 400 错误请求,字段为必填项

转载 作者:行者123 更新时间:2023-12-02 23:06:35 24 4
gpt4 key购买 nike

我正在尝试使用 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]

Image of the error

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

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

Insomnia

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

最佳答案

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

将解析器设置为 JSONParser 解决了该问题。

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

REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}

从 Axios 发送请求时,还将 header 设置为 json。

headers: {
'Content-Type': 'application/json'
}

感谢您的帮助!

关于javascript - 从 Axios 到 Django 的 400 错误请求,字段为必填项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57562494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com