1
votes

I'm trying to send a POST request from my React frontend using Axios

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:

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

Image of the error

I am using the Django REST framework in my Django Backend for authentication.

Everything works fine using Insomnia but any requests through React results in a "Bad Request"

Insomnia

django-cors-headers has been installed and configured as well.

1
Can you check the exact headers in insomnia and see the difference with ones you use in axios? Maybe...Hero Qu
Possible duplicate of axios post request to send form dataLinovia

1 Answers

1
votes

Answering my own question here.

Setting the parser to JSONParser solved the issue.

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.

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

Thankyou who tried to help!