background
基于django和react构建开发环境:
- django+restframework作为后台API提供者
- 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-headersand 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'sCommonMiddleware
or Whitenoise'sWhiteNoiseMiddleware
. 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", ]