![](/img/trans.png)
[英]Blocked by CORS policy: No"Access-Control-Allow-Origin" Using Flask
[英]Axios blocked by CORS policy with Django REST Framework: 'Access-Control-Allow-Origin' header in the response must not be wildcard
Using vuejs3 ans axios, I'm trying to make a API call out to a django project, and getting a CORS error on the chrome side. 不知道我在这里缺少什么设置...
返回的预检 OPTIONS 响应正常,但 chrome 对'Access-Control-Allow-Origin'
header 为“*”感到不安。
我正在使用 django-rest-framework 和django-cors-headers
。
django.settings:
ALLOWED_HOSTS = ["*"]
# CORS
CORS_ALLOW_ALL_ORIGINS = False # was initially True
CORS_ALLOW_HEADERS = "*"
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ["https://mydomain", "http://localhost:8080", "http://127.0.0.1:8080"]
# Application definition
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"corsheaders",
...
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
...
]
vuejs/axios 方面:
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.withCredentials = true;
const url = `https://mydomin/my/endpoint/`;
response = axios.get(url);
我认为将CORS_ALLOW_ALL_ORIGINS
设置为False
并定义CORS_ALLOWED_ORIGINS
值可以解决问题,但Access-Control-Allow-Origin
header 仍显示为“*”。
我错过了一个设置吗?
尝试 CORS_ALLOW_HEADERS 作为这样的列表
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
CORS_ALLOW_HEADERS
更改为此。 我试过了,工作了
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"content-disposition",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
也许其他中间件阻止 CORS 中间件设置 header。 该文档指出:
CorsMiddleware 应该放在尽可能高的位置,尤其是在任何可以生成响应的中间件之前,例如 Django 的 CommonMiddleware 或 Whitenoise 的 WhiteNoiseMiddleware。 如果不是之前,它将无法将 CORS 标头添加到这些响应中。
所以尝试改变中间件的顺序,比如:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
...
]
您的 http 请求的标头中有什么? 如果它还没有的话,它可能有助于包含“”Access-Control-Allow-Origin”:“*”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.