Tyler
Tyler

Reputation: 438

ReactJS not displaying Django REST Framework API data

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.

Upvotes: 0

Views: 2069

Answers (2)

Tyler
Tyler

Reputation: 438

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

Upvotes: 1

j3py
j3py

Reputation: 1257

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

Upvotes: 1

Related Questions