程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django CORS cross domain problem

編輯:Python

Django cors Cross-domain problem

Cross domain issues in front and back end separation projects That is, homology strategy

The same-origin policy : The same-origin policy /SOP(Same origin policy) It's a convention , from Netscape company 1995 Browser introduced in , It is the core and most basic security feature of the browser , All support now JavaScript All browsers of will use this strategy . If the same origin policy is missing , Browsers are easily accessible XSS、 CSFR Such attacks .

Homologous refers to " agreement + domain name + port " All the same , Even if two different domains point to the same one ip Address , Nor a homologous .

Source is protocol 、 Domain name and port number .

agreement :http,https

Cross domain : The front end requests URL The agreement 、 domain name 、 Port and front page URL The difference is cross domain

stay Django Solve cross domain problems in

One 、

# 1、 Install third party libraries django-cors-headers
# 2、 stay settings.py Add 'corsheaders.middleware.CorsMiddleware', stay SessionMiddleware and CommonMiddleware In the middle of the
# 3、 stay INSTALLED_APPS Add in “corsheaders” INSTALLED_APPS = [
'search.apps.SearchConfig',
'data.apps.DataConfig',
'record_data.apps.RecordDataConfig',
'deleted_data.apps.DeletedDataConfig',
'mgmt.apps.MgmtConfig',
'c_test.apps.CTestConfig',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders', # newly added
] # 4、 Add... To the middleware corsheaders.middleware.CorsMiddleware,django.middleware.common.CommonMiddleware MIDDLEWARE = [
# 'utils.middleware.ExceptionMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', # newly added / Must be in common Middleware
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] # 5、 stay settings.py Bottom increase CORS_ALLOW_CREDENTIALS = True # Allowed to carry cookie
CORS_ORIGIN_ALLOW_ALL = True # Release all
CORS_ORIGIN_WHITELIST = ('*') # White list # CORS_ALLOW_METHODS: String list , What are allowed HTTP Request method .
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
) # CORS_ALLOW_HEADERS: String list , What non-standard HTTP Request header .
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)

Two 、

# You can register a middleware by yourself , In middleware process_response Method for response encapsulate 
def process_response(self, request, response):
response["Content-Type"] = "application/json" # The content format of the response message
response["Access-Control-Allow-Origin"] = "*" # Source address that allows cross domain requests , * Express : Allow all addresses
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" # Specific methods to allow cross domain requests
response["Access-Control-Max-Age"] = "1000" # Used to specify the validity period of this pre inspection request , The unit is in seconds ,, In the meantime, there is no need to send another pre check request .
response["Access-Control-Allow-Headers"] = "*"
return response
  • The cross domain implementation process is

    1、 The browser will first send options The request asks whether the backend allows cross domain , The backend queries whether these two domain names are in the white list

    2、 If the domain name is in the white list, inform the browser in the response result that cross domain is allowed

    3、 The browser sends for the second time post request , Carry the user login data to the backend , Complete login verification

Django cors More articles on cross domain issues

  1. Django CORS Cross-domain resource sharing

    1, What is? CORS ​ Allow browsers to cross source ( agreement + domain name + port ) The server sends out XMLHttpRequest request , To overcome AJAX A restriction that can only be used with the same origin 2, characteristic ​ 1, Browser auto complete ( Add a special in the request header ...

  2. django Class notes 7-jQuery Ajax and Native Ajax- fake Ajax- Three Ajax Upload file method -JSONP and CORS Cross-domain resource sharing

    One .jQuery Ajax and Native Ajax from django.conf.urls import url from django.contrib import admin from app01 ...

  3. Browser homology strategy and CORS Cross-domain solutions DRF

    The definition of a source If two pages of the protocol , port ( If there is a designation ) It's the same as the domain name , The two pages have the same source . for instance : The table below shows the relative http://a.xyz.com/dir/page.html Examples of homology detection : UR ...

  4. 4 false ajax:jsonp、cors Cross-domain request

    One . The same-origin policy https://www.cnblogs.com/yuanchenqi/articles/7638956.html The same-origin policy (Same origin policy) It's a convention , It's the most ...

  5. Django Framework insight _05 (Django Cache in 、Django Solve cross domain processes ( It's not a simple request , A simple request )、 Automatically generate interface documentation )

    One .Django Cache in : Foreplay : In dynamic websites , All user requests , The server will go to the database for corresponding increment , Delete , check , Change , Apply colours to a drawing template , Execute business logic , Finally, generate the page that the user sees . When a website has a large number of users , each ...

  6. Django Handle cross domain configuration 、 Front desk processing ajax

    One . Django To deal with cross domain There are many cross domain approaches , The most used is CORS( Cross-domain resource sharing ), Next, let's briefly mention django Handle cross domain configuration in . First installation django-cors-headers modular : pip ...

  7. django Cross-domain configuration

    1. Cross domain principle #1. First, the browser security policy limits js ajax Cross domain access server #2. If the header information returned by the server contains the current domain : // allow http://localhost:8080 In the page that this website opens j ...

  8. django Configure cross domain and develop test interfaces

    1. Create a test project 1.1 Create projects and APP django-admin startproject BookManage # Create project python manage.py startapp books ...

  9. 02.django Configure cross domain and develop test interfaces

    1. Create a test project   1.1 Create projects and APP   '''1. Create projects and APP''' django-admin startproject BookManage # Create project python mana ...

  10. day3(django Configure cross domain )

    1. Crossing principle 1. First, the browser security policy limits js ajax Cross domain access server 2. If the header information returned by the server contains the current domain : // allow http://localhost:8080 In the page that this website opens js interview ...

Random recommendation

  1. Realization PageProcessor

    4.1 Realization PageProcessor In this part, we go directly through GithubRepoPageProcessor This example introduces PageProcessor The way of writing . I will PageProcessor The customization of is divided into three ...

  2. Linq Operation basis

    Reference material : LINQ series :LINQ to DataSet Of DataTable operation List<T> Convert to DataTable C# DataTable and List The method of mutual conversion between Linq in ...

  3. SQL Statement table building 、 Set primary key 、 Foreign keys 、check、default、unique constraint

    · What is a database ? A warehouse for storing data . · What's the difference between a database and a data structure ? Data structure to solve the problem of operating data in memory , Database to solve the problem of operating data in the hard disk . Data structure studies some abstract data models (ADT) And as well as defined in the module ...

  4. staging server, source congtrol, deply workflow using git

    web Project under development , There are three practices that are very important to the success of a project : 1. staging servers 2. Version control workflows 3. Tested, repeatable de ...

  5. BZOJ_1609_[Usaco2008_Feb]_Eating_Together_ A troublesome dinner party _( Dynamic programming ,LIS)

    describe http://www.lydsy.com/JudgeOnline/problem.php?id=1609 Give a string of 1,2,3 The number of components , Find out how many numbers need to be changed at least , Make it a non descending or non ascending sequence . analysis Law ...

  6. Network flow ( Maximum flow )CodeForces 512C:Fox And Dinner

    Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). T ...

  7. Vs2015 Ef Connect Oracle appear OracleInternal.Common.ConfigBaseClass Solutions for

    If the configuration is OK , Namely  Oracle.ManagedDataAccess In the global assembly version problem Solution take Oracle.ManagedDataAccess  GAC Remove from global assembly 1: use C ...

  8. CharSequence Of getText() And String Of getString()( turn )

    CharSequence Of getText() And String Of getString()『Android Series seven 』 I met two ways to get constants in my study : CharSequence chrs = getText ...

  9. front end -----jQuery Selector

    02-jQuery Selector   We used to be CSS The selectors in learning are : Let's learn about it today jQuery Selectors . jQuery The selector is jQuery Strong embodiment , It provides a set of methods , Let's get the meta information in the page more easily ...

  10. linux Daily orders (39):lsof command

    lsof(list open files) Is a list of the current system open file tools . stay linux In the environment , Everything exists in the form of documents , Files provide more than just regular data access , You can also access network connections and hardware . So transmission control protocol ...


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved