使用 vuejs3 和 axios,我尝试对部署到 AWS API Gateway 的 django 项目进行 API 调用,并在 chrome 端收到 CORS 错误。不确定我在这里缺少什么设置...
返回的预检 OPTIONS 响应正常,但 chrome 因
'Access-Control-Allow-Origin'
标头为“*”而感到不安。
我正在使用 django-rest-framework 和
django-cors-headers
。
django.设置:
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
标题仍然显示为“*”。
我是否缺少设置?
尝试将 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 中间件设置标头。 文档指出:
CorsMiddleware 应尽可能放在高处,尤其是之前 任何可以生成响应的中间件,例如 Django CommonMiddleware 或 Whitenoise 的 WhiteNoiseMiddleware。如果不是 之前,它将无法将 CORS 标头添加到这些 回应。
所以尝试改变中间件的顺序,比如:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
...
]
尝试以下操作:
一:
确保您的中间件如下
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
两个
settings.py 中的 CORS 设置应如下所示,注意白名单。这有助于保护您的 API 免受任何访问,但要使其正常工作,请使用注释块
CORS_ALLOW_HEADERS = "*"
CORS_ORIGIN_WHITELIST = [
'http://127.0.0.1:5173',
]
# CORS_ORIGIN_ALLOW_ALL = True
三
Vue JS get 请求可以如下
async login() {
const response = await axios.get('url');
console.log(response)
},
希望有帮助。
我面临着同样的问题,最后我通过将 CORS_ORIGIN_ALLOW_ALL 设置为 false 并将我的本地 url 添加到 CORS_ALLOWED_ORIGINS 来解决:
CORS_ALLOWED_ORIGINS = [ “http://localhost:5173”, ] CORS_ORIGIN_ALLOW_ALL = False
最后在 axios 的请求配置中将 withCredentials 设置为 false:
response = axios.get(url, {withCredentials: false,});