【问题标题】:ReactJS with graphql CORS Issue with django backendReactJS with graphql CORS Django后端问题
【发布时间】:2022-02-17 21:19:29
【问题描述】:
我在http://127.0.0.1:8000 上运行django 后端,我想通过reactjs 前端请求它。
如下所示,我可以在Insomnia 应用中看到成功响应。
但是,当我想要一个带有 reactjs 前端的请求时,我得到一个 CORS ERROR。
我在检查网络中检查了请求,我看到了一个类似的失眠请求负载。
【问题讨论】:
标签:
reactjs
django
graphql
apollo-client
【解决方案1】:
- 安装
django-cors-headers:
pip install django-cors-headers
- 在
settings.py 中添加corsheaders 到INSTALLED_APPS:
INSTALLED_APPS = [
...,
"corsheaders",
...,
]
- 将
CorsMiddleware 添加到settings.py 中的中间件:
MIDDLEWARE = [
...,
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
...,
]
- 现在您可以像这样在
settings.py 中设置允许的来源:
CORS_ALLOWED_ORIGINS = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000",
]
更多信息请参阅link。