简体   繁体   English

从Axios到Django的400错误请求,必填字段

[英]400 Bad Request from Axios to Django, field is required

I'm trying to send a POST request from my React frontend using Axios 我正在尝试使用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)
});

No matter what I do, I get a 400 Bad Request in response stating: 无论我做什么,我都会收到一个400错误的请求,指出:

"username":[This field is required],
"password":[This field is required]

错误图片

I am using the Django REST framework in my Django Backend for authentication. 我在Django后端中使用Django REST框架进行身份验证。

Everything works fine using Insomnia but any requests through React results in a "Bad Request" 使用Insomnia一切都可以正常工作,但是任何通过React的请求都会导致“错误请求”

失眠

django-cors-headers has been installed and configured as well. django-cors-headers也已安装和配置。

Answering my own question here. 在这里回答我自己的问题。

Setting the parser to JSONParser solved the issue. 将解析器设置为JSONParser解决此问题。

Setting it projectwide is the best option - 最好在整个项目范围内进行设置-

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

Also set the header to json while sending request from Axios. 在从Axios发送请求时,还将标头设置为json。

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

Thankyou who tried to help! 谢谢谁的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM