0

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!

Toruitas
  • 136
  • 1
  • 7
  • Did yo try to use `fetch` and `response => response.json()`. – Sergey Pugach Jan 21 '19 at 12:26
  • Yes, unfortunately the following code also returns `fetch('https://dog.ceo/api/breeds/image/random', { method:'GET', headers: { Accept: 'application/json', }, }) .then(response => { console.log("dummy response",response); response.json().then(json => { console.log("dummy",json); }); });` – Toruitas Jan 21 '19 at 13:22

1 Answers1

1

This turned out to be a Firefox issue, not a React or DRF issue. Related to: Object 'unavailable' in Firefox console

By using the first example in the first answer, I was able to get it to properly display in the browser console:

axios.get('/api/dummy/') .then((response) => console.log("Data",JSON.stringify(response, null, 4)));

Toruitas
  • 136
  • 1
  • 7