zoukankan      html  css  js  c++  java
  • 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/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
  • 相关阅读:
    MySQL 操作命令梳理(5)-执行sql语句查询即mysql状态说明
    MySQL 主从同步(5)-同步延迟状态考量(seconds_behind_master和pt-heartbea)
    MySQL 操作命令梳理(4)-中文乱码问题
    WebAssembly 介绍
    Android MVP
    Android Data Binding(数据绑定)用户指南
    认知心理学告诉你什么才是高效学习
    Android O新特性和行为变更总结zz
    音视频不同步问题的原因和解决方案
    当程序员写不出代码了,该怎么办?
  • 原文地址:https://www.cnblogs.com/lightsong/p/15488450.html
Copyright © 2011-2022 走看看