'What is the proper way to send a json body with axios from React to Django Rest Api
I am trying to send a post request to my django rest API using Axios from a react frontend.
Home.js
Here I am getting the value from the form and setting up the state and sending the value to the function that will call the API on submit
const [query, setQuery] = useState({
search: "",
})
const { search } = query;
// function handle submit
const onSubmit = (e) => {
e.preventDefault();
console.log(search);
navigate(`/search/${search}`);
fetchSearch(search); //fucntion that deals with the api call
};
searchApi.js this function deals with api call
export const fetchSearch = async (search) => {
console.log("the data being recieved ", search);
const config = {
header: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify({ search }); // 1
const body = { // 2
search: search,
};
console.log("this is the body", body);
try {
let response = await axios.post(`${url}/get-teacher/`, body, config);
console.log(response.data);
} catch (error) {
console.log(error);
}
};
Now let me tell you the problem I am facing, as shown above, I have comments beside the body. If I send the body //1 as a request, then django throws this error and I get an internal server error
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
And if I send the body //2 as a request then it works perfectly.
the view that handles the request
@api_view(['POST'])
def search(request):
query = request.data.get('search')
print("this is the query recieved" ,query)
if query is not None:
try:
user = TeacherDetail.objects.filter(is_verified= True)
# to chain lookups to query multiple fields at once
lookups = Q(name__icontains = query) | Q(location__icontains = query) | Q(full_address__icontains = query) | Q(name_of_school__icontains = query) | Q(experience__icontains = query) | Q(teach_for_no_days__icontains = query) | Q(subject__icontains = query) | Q(shift__icontains = query) | Q(teach_class__icontains = query) | Q(board__icontains = query)
user = user.filter(lookups)
serializer = TeacherDetailSerializer(user, many = True)
return Response(serializer.data)
except Exception as e:
e = str(e)
return Response({'status':status.HTTP_404_NOT_FOUND, "message": e})
else:
response = {
"message": "Query is empty",
"status": status.HTTP_404_NOT_FOUND
}
I want to know why this is happening because when I console.log() the body //1 is see
{"search":"swastika"}
which is exactly what we send to the body of the request.
Please correct me where I am wrong and tell me the proper way to send the body as JSON
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
