【问题标题】:Django+React integrationDjango+React 集成
【发布时间】:2020-09-25 17:37:52
【问题描述】:

我有 Django Rest Framework 服务器在一个终端中运行,而 React 在另一个终端中运行。

我使用 axios 在 React 中使用 Django API,如下所述

    axios.get('http://localhost:8000/songs/').then(res=>console.log(res)

效果很好,在生产模式下,我会将 main.js(由 npm run build 创建,React 的构建文件)挂钩到 Django 模板。

这种方法可以在服务器中使用吗?推荐吗?

我曾经将 Django + React 与这个 guid (https://www.valentinog.com/blog/drf/) 集成,但它不支持某些 npm 包

【问题讨论】:

    标签: reactjs django-rest-framework django-react


    【解决方案1】:

    在包含所有 api 端点 URL 的 src react 文件夹中创建 constant.js 文件。像这样:

    const localhost = 'http://127.0.0.1:8000';
    
    const apiURL = '/api';
    
    export const endpoint = `${localhost}${apiURL}`;
    
    export const productListURL = `${endpoint}/products/`;
    export const productDetailURL = id => `${endpoint}/products/${id}/`;
    export const addToCartURL = `${endpoint}/add-to-cart/`;
    export const orderSummaryURL = `${endpoint}/order-summary/`;
    
    

    否则,您将不得不在前端的每个请求上更改端点域,这可能很耗时。

    我在实际的网络服务器上部署应用程序,例如;数字海洋上的 ubuntu droplet,使用 NGINX。 您可以将 react 和 Django 应用程序部署在同一个 droplet 上。你只需要为 nginx 编写额外的配置。并正确配置网络服务器。

    react 部署文档: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-react-application-to-digitalocean-app-platform

    django 部署文档: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04

    完成这两个教程后,您将了解如何为 MVC 配置 nginx。

    【讨论】:

      【解决方案2】:

      是的,它会起作用的。有几种方法可以同时部署 React 和 Django。

      但是,我更喜欢部署它的方法是使用docker-compose 并使用 nginx 反向代理进行部署。

      您能否详细说明为什么 Valentino Gagliardi 教程中不支持某些 npm 包?

      【讨论】:

      • 感谢您的回答,我学会了更新 webpack 以支持 sass 和 typescript 文件
      【解决方案3】:

      找到有用的文档

      https://cuckootechnologies.medium.com/integrating-django-rest-framework-with-react-js-9bf9d7f051a1

      Django 将在一个终端中运行,而 React 将在另一个终端中运行。来自 Django 服务器的 API 将由 React 使用 Axios 使用。

      【讨论】:

        猜你喜欢
        • 2021-09-15
        • 1970-01-01
        • 2019-03-21
        • 2022-11-03
        • 2017-09-24
        • 1970-01-01
        • 2022-07-31
        • 1970-01-01
        • 2014-02-23
        相关资源
        最近更新 更多