0

I am running React JS with the Nginx server, and would like to connect with the Django REST API running with Gunicorn. When I call the page http://18.220.194.77/ gunicorn shows the GET with code 200, but the data is not updated, if I access http://18.220.194.77:8000/api/ I can see Django working, below settings:

Nginx:

server {
   listen 80 default_server;
   server_name 18.220.194.77;
   root /var/www/frontend/build;

   location /api {
        proxy_pass http://18.220.194.77:8000;  # this is where you point it to the Django server
    }

   location / {
        try_files $uri $uri/ /index.html; # this is where you serve the React build
    }
}

React served by Django:

import React, { Component } from 'react';

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

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

  render() {
    return (
      <div>
        {this.state.todos.map(item => (
          <div key={item.id}>
            <h1>{item.title}</h1>
            <span>{item.description}</span>
          </div>
        ))}
      </div>
    );
  }
}

export default App;

1 Answer 1

1

Since your frontend and backend are on different origins, you'll need to set up CORS headers on the backend to allow your frontend access.

https://github.com/ottoyiu/django-cors-headers is a battle-tested library for that.

Sign up to request clarification or add additional context in comments.

2 Comments

I have CORS in Django, INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] but it does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.