• Integration of hot-load django dev sever and hot-load reactjs dev server


    background

    基于django和react构建开发环境:

    1. django+restframework作为后台API提供者
    2. react+ant design作为前端UI框架

    利用django和react的开发工具的热更新功能, 实现前后台代码更新都不需要手动重启server。

    如下拓扑图。

    首先,浏览器从 react dev server上请求前端脚本,

    然后 前端脚本 访问 django dev server 的 restful和websocket接口。

    这就牵扯到跨域访问问题, 需要在django dev server上开启对react dev server的域名许可。

    django

    pipenv run python3 manage.py runserver

    react

    npm start

    Topology

    域访问许可响应报文头

    https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

    Access-Control-Allow-Origin

    Access-Control-Allow-Origin 响应头指定了该响应的资源是否被允许与给定的origin共享。

    语法

    Access-Control-Allow-Origin: *
    Access-Control-Allow-Origin: <origin>
    

    django CORS plugin

    https://github.com/adamchainz/django-cors-headers

    https://pypi.org/project/django-cors-headers/

    A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django application from other origins.

    About CORS

    Adding CORS headers allows your resources to be accessed on other domains. It’s important you understand the implications before adding the headers, since you could be unintentionally opening up your site’s private data to others.

    设置

    CorsMiddleware 必须放在 CommonMiddleware 之前。

    Install from pip:

    python -m pip install django-cors-headers

    and then add it to your installed apps:

    INSTALLED_APPS = [
        ...,
        "corsheaders",
        ...,
    ]

    Make sure you add the trailing comma or you might get a ModuleNotFoundError (see this blog post).

    You will also need to add a middleware class to listen in on responses:

    MIDDLEWARE = [
        ...,
        "corsheaders.middleware.CorsMiddleware",
        "django.middleware.common.CommonMiddleware",
        ...,
    ]

    CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware or Whitenoise's WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

    在django的setting文件中,配置允许的域名列表

    CORS_ALLOWED_ORIGINS = [
        "https://example.com",
        "https://sub.example.com",
        "http://localhost:8080",
        "http://127.0.0.1:9000",
    ]
    出处:http://www.cnblogs.com/lightsong/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
  • 相关阅读:
    Oracle 的四种连接-左外连接、右外连接、内连接、全连接
    选择文件错误提示
    window 窗口编辑
    BufferedWriter与BufferedRead --------------------------Test2
    BufferedWriter与BufferedRead --------------------------Test
    BufferedInputStream 缓冲输入字节流 -------上
    IO异常 的处理 test
    IO异常 的处理
    Struts2概述、开发环境搭建
    Operation(自定义多线程)
  • 原文地址:https://www.cnblogs.com/lightsong/p/15488450.html
Copyright © 2020-2023  润新知