如何将React与Django REST连接?

时间:2018-11-09 16:36:57

标签: python django reactjs amazon-web-services django-rest-framework

我正在Nginx服务器上运行React JS,并想与运行Gunicorn的Django REST API连接。当我调用页面http://18.220.194.77/时,gunicorn显示代码为200的GET,但数据未更新,如果我访问http://18.220.194.77:8000/api/,可以看到Django在以下设置下正常工作:

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
    }
}

由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 个答案:

答案 0 :(得分:1)

由于前端和后端位于不同的origins上,因此您需要在后端设置CORS标头以允许您的前端访问。

https://github.com/ottoyiu/django-cors-headers是经过考验的库。