【问题标题】:How to connect React with Django REST?如何将 React 与 Django REST 连接起来?
【发布时间】:2018-11-09 16:36:57
【问题描述】:

我正在使用 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 提供的 React:

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;

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 我在 Django 中有 CORS,INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ]但它不起作用。
    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2020-10-10
    • 2021-11-01
    • 2021-06-04
    • 1970-01-01
    • 2017-11-07
    相关资源
    最近更新 更多