问题描述
如何在我的 Django REST 框架上启用 CORS?reference 没有多大帮助,它说我可以通过中间件来做,但我该怎么做呢?
How can I enable CORS on my Django REST Framework? the reference doesn't help much, it says that I can do by a middleware, but how can I do that?
推荐答案
您在问题中引用的链接建议使用 django-cors-headers
,其 文档说要安装库
The link you referenced in your question recommends using django-cors-headers
, whose documentation says to install the library
python -m pip install django-cors-headers
然后将其添加到您安装的应用程序中:
and then add it to your installed apps:
INSTALLED_APPS = (
...
'corsheaders',
...
)
您还需要添加一个中间件类来监听响应:
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE = [
...,
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...,
]
并为 CORS 指定域,例如:
and specify domains for CORS, e.g.:
CORS_ALLOWED_ORIGINS = [
'http://localhost:3030',
]
请浏览其文档的配置部分,特别注意各种 CORS_ORIGIN_
设置.您需要根据自己的需要设置其中的一些.
Please browse the configuration section of its documentation, paying particular attention to the various CORS_ORIGIN_
settings. You'll need to set some of those based on your needs.
这篇关于如何在 Django REST 框架上启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!