0
votes

I am trying to use ReactJS to build a simple website that pulls data from my Django REST Framework API. The issue I am running into, is that my data is not being output by React. I am certain that my Django backend is running flawlessly. I get no errors when running it, and can view my API data via "http://127.0.0.1:8000/api/".

Here is my frontend ReactJS code:

import React, { Component } from 'react';

class App extends Component {
    state = {
        usernames : []
    };


    async componentDidMount() {
        try { 
            const res = await fetch('http://127.0.0.1:8000/api/');
            const usernames = await res.json();
            this.setState({
                usernames
            });
        } catch (e) {
            console.log(e);
        }
    }

    render() {
        return(
            <div>
                {this.state.usernames.map(item => (
                    <div key={item.id}>
                        <h1>{item.username}</h1>                    
                    </div>
                ))}
            </div>
       );
    }
}

export default App

I have tried updated my CORS_ORIGIN_WHITELIST via settings.py and includes all variations of localhost.

When scripting with Python, I am able to make a request and retrieve my API data. This is the output:

[{'username': 'testname', 'created_at': '2019-12-06T00:03:50.833429Z'}, {'username': 'testname2', 'created_at': '2019-12-06T00:04:01.906974Z'}, {'username': 'testname3', 'created_at': '2019-12-06T00:04:05.330933Z'}, {'username': 'testname4', 'created_at': '2019-12-06T00:04:08.144381Z'}]

And though no ID is present in the output (Which I'm not sure why) I can still access the correct data by making a request like this: "http://127.0.0.1:8000/api/3/"

Any help is appreciated.

2
Do you get any client side errors in your browser's developer tools? How about if you remove the item.id reference since you already know it's not in your JSON object? - j3py
I am seeing these errors: Access to fetch at '127.0.0.1:8000/api' from origin 'localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. - Tyler
But I have CORS setup properly in django settings - Tyler
Did you try setting Access-Control-Allow-Origin: * just for the purposes of local development? Obviously, you don't want to do that in general, but doing it on your local machine while you're dev'ing is fine. See here if you are unsure of how to: techiediaries.com/django-cors - j3py
You're welcome! - j3py

2 Answers

1
votes

Set Access-Control-Allow-Origin: to * just for the purposes of local development. For security reasons you don't want to do that in production, but doing it on your local machine while you're dev'ing is fine. See here if you are unsure of how to: techiediaries.com/django-cors

1
votes

To solve this issue, I had to install django-cors-headers. This can be done via pip install django-cors-headers

After that, I had to add the following to my settings.py file:

INSTALLED_APPS = [
    ##...
    'corsheaders'
]

MIDDLEWARE_CLASSES = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.BrokenLinkEmailsMiddleware',
    'django.middleware.common.CommonMiddleware',
    #...
]

CORS_ORIGIN_ALLOW_ALL = True