服务器部署新人,自己使用django+nginx+uwsgi的模式把自己的项目部署到服务器之后,
可以访问自己的登录页面,但是在提交表单的时候(向http://127.0.0.1:8000/login/ 这个地址使用ajax发送了一个POST请求)firefox报跨源错误,如下
在网上查了大量的博客和教程,主要都是两种解决方法。一是使用django-cors-headers的方法,修改django项目的settings.py文件;二是修改nginx配置文件,
添加add_header 'Access-Control-Allow-Origin' '*';之类的头。但两类方法
都不奏效,不知道是不是我写错了(jsonp就不说了,那个只能用于get)几个
文件的关键代码如下,希望大家给点提示
nginx的server设置(默认监听80端口)
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
include /etc/nginx/uwsgi_params;
uwsgi_pass 127.0.0.1:8000;
}
django的settings.py文件
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'upload',
'show',
'makeSet',
'login',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'*'
)
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)