一 使用環境: windows 7 64位操作系統
二 jango-cors-headers安裝解決跨域問題(后端解決方案)
- 跨域,指的是瀏覽器不能執行其他網站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器施加的安全限制。
- 所謂同源是指,域名,協議,端口均相同,不明白沒關系,舉個栗子:
- http://www.123.com/index.html 調用 http://www.123.com/server.php (非跨域)
- http://www.123.com/index.html 調用 http://www.456.com/server.php (主域名不同:123/456,跨域)
- http://abc.123.com/index.html 調用 http://def.123.com/server.php (子域名不同:abc/def,跨域)
- http://www.123.com:8080/index.html 調用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)
- http://www.123.com/index.html 調用 https://www.123.com/server.php (協議不同:http/https,跨域)
- 127.0.0.1:8000與127.0.0.1:8001(端口不同,跨域)
- 請注意:localhost和127.0.0.1雖然都指向本機,但也屬於跨域。
- 瀏覽器執行javascript腳本時,會檢查這個腳本屬於哪個頁面,如果不是同源頁面,就不會被執行。
1.查看文檔: https://github.com/adamchainz/django-cors-headers
2.按裝: python -m pip install django-cors-headers
3.添加到setting的app中
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', # admin依賴 'django.contrib.contenttypes', # admin依賴 'django.contrib.sessions', # admin依賴 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # 跨域設置4-(1-2):按裝,注冊跨域包(django-cors-headers),中間件中注冊 ]
4.添加中間件
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', # 跨域設置4-3:跨域中間件,要放到csrf中間件前面 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
5.setting下面添加下面的配置
# 跨域設置4-4:添加跨域設置 # 指明在跨域訪問中,后端是否支持對cookie的操作 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', 'Pragma', 'x-token', ) # 跨域設置4-4:添加跨域設置end
6.文檔通過瀏覽翻譯成中文



