Django-cors-header解决同源策略限制下的跨域请求
浏览器有同源策略限制,导致发送ajax请求时无法接收数据+跨域存在。 Django-cors-headers用于解决Django跨域请求问题。 ? 1) 所需设置
在 Django 设置中配置中间件的行为。必须至少设置以下三项之一:
CORS_ALLOWED_ORIGINSCORS_ALLOWED_ORIGIN_REGEXESCORS_ALLOW_ALL_ORIGINS
1.CORS_ALLOWED_ORIGINS:
可以发出跨站点 HTTP 请求的源列表。默认端口(HTTPS=443、HTTP=80)是可选的。以前,此方法别名为 CORS_ORIGIN_WHITELIST。
CORS_ALLOWED_ORIGINS = ["https://example.com","https://sub.example.com","http://localhost:8080","http://127.0.0.1:9000",]
2.CORS_ALLOWED_ORIGIN_REGEXES:sequence[str|pattern[str]]
表示与起源的正则表达式匹配的字符串列表,可以发出跨站HTTP请求。默认为[]。当存在大量子域时,CORS_ALLOWED_ORIGIN 很有用。以前,此设置称为 CORS_ORIGIN_REGEX_WHITELIST。
CORS_ALLOWED_ORIGIN_REGEXES = [r"^https://\w+\.example\.com$",]
3.CORS_ALLOW_ALL_ORIGIN S:布尔值
如果为 True,则允许所有源。限制允许来源的其他设置将被忽略。默认为 false。将其设置为 True 可能很危险,因为它允许任何网站向您的网站发出跨域请求。通常,您必须使用 CORS_ALLOWED_ORIGIN 或 CORS_ALLOWED_ORIGIN_REGEXES 来限制允许的源列表。
以前此设置称为 CORS_ORIGIN_ALLOW_ALL。
3。可选设置,默认值基本够用。
1.CORS_ALLOW_METHODS 请求允许的 HTTP 操作列表。
CORS_ALLOW_METHODS = ("DELETE","GET","OPTIONS","PATCH","POST","PUT",)
默认值可以导入为 corsheaders.defaults.default_methods,自定义扩展如下:
from corsheaders.defaults import default_methodsCORS_ALLOW_METHODS = (*default_methods,"POKE",)
2.CORS_ALLOW_HEADERS 浏览器请求中允许的非标准 HTTP 请求头列表。设置访问控制允许请求标头以响应预检请求。
默认为:
CORS_ALLOW_HEADERS = ("accept","authorization","content-type","user-agent","x-csrftoken","x-requested-with",)
默认值可以导入为corsheaders.defaults.default_headers,自定义扩展如下:
from corsheaders.defaults import default_headersCORS_ALLOW_HEADERS = (*default_headers,"my-custom-header",)
IV。 CSRF 集成
大多数站点需要通过使用跨站点请求伪造来保护 Django 请求。 CORS 和 CSRF 是分开的。 Django 无法使用 CORS 配置来避免站点引用检查。如果需要使用,需要设置CSRF_TRUSTED_ORIGIN S。例如:
CORS_ALLOWED_ORIGINS = ["https://read-only.example.com","https://read-and-write.example.com",]CSRF_TRUSTED_ORIGINS = ["https://read-and-write.example.com",]
5. 与信号一起使用
如果附加到信号的处理程序返回真值,则允许该请求。
例如,自定义如下处理程序:
# myapp/handlers.pyfrom corsheaders.signals import check_request_enabledfrom myapp.models import MySitedef cors_allow_mysites(sender, request, **kwargs):return MySite.objects.filter(host=request.headers["origin"]).exists()check_request_enabled.connect(cors_allow_mysites)
然后在应用程序准备就绪时使用 Django AppConfig 连接它:
# myapp/__init__.pydefault_app_config = "myapp.apps.MyAppConfig"
# myapp/apps.pyfrom django.apps import AppConfigclass MyAppConfig(AppConfig):name = "myapp"def ready(self):# Makes sure all signal handlers are connectedfrom myapp import handlers # noqa
信号的常见用例是所有❓来源允许子集URL,而一组通用的源允许访问所有 URL。首先将 CORS_ALLOWED_ORIGIN 设置为允许访问任何 URL 的可信源列表,然后将处理程序添加到 check_request_enabled 以允许 CORS,而不管不受限制的 URL。例如: 参考文档: https://github.com/adamchainz/django-cors-headers# myapp/handlers.pyfrom corsheaders.signals import check_request_enabled
def cors_allow_api_to_everyone(sender, request, **kwargs): return request.path.startswith("/api/")
check_request_enabled.connect(cors_allow_api_to_everyone)
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
code前端网
