I'm trying to use React to consume a Django Rest Framework-based API, but am having some major problems with what should be super simple.
Given this simple API method:
from rest_framework.decorators import api_view, detail_route, list_route, permission_classes
@api_view(['GET'])
@permission_classes((AllowAny,))
def dummy(request, per_page=40):
import json
print("Returning the dummy")
return Response({"Yeah":"Booo!"})
And this function in React using Axios to consume it:
import React, { Component } from "react";
import PropTypes from "prop-types";
import axios from 'axios';
class Dashboard extends Component{
constructor(props){
super(props);
this.state = {
username: props.username,
};
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
}
componentDidMount(){
axios.get('/api/dummy/').then((response) => console.log(response));
}
render(){
return(
<div id="dashboardWrapper"></div>
)
}
}
export default Dashboard
Using Python's requests library and curl, the method returns a JSON object. In the browser, loading this page will run the GET function, and also load the JSON object in the Network tab. This leads me to believe that the problem isn't on Django's end. Additionally, I tried this with a third-party API (https://dog.ceo/api/breeds/image/random) and get the same problem.
When I look in the console, the Axios GET function will not capture the response sent up from Django. It gets a status code 200, but nothing else. No response.data at all. With console.log(response) all I see is , for both errors (have tested on non-existant endpoints) and valid endpoints.
Using Fetch gets the same result.
Strangely enough, Axios POST works but also doesn't capture any response afterwards.
What could the cause and solution be? Thanks for the help!