This is the 24th day of my participation in the August More Text Challenge

Life is too short to learn Python together

The same-origin policy

Same-origin policy:

It is the core and most basic security function of the browser. If the same origin policy is missing, the normal function of the browser may be affected. It can be said that the Web is built on the basis of the same origin policy. The browser is only an implementation of the same origin policy. It is the browser that intercepts the access results.

The requested URL must be in the same domain as the url on the browser, i.e. the domain name, port, and protocol.

For example, if my local domain name is 127.0.0.1:8000, I request another domain name: 127.0.0.1:8001

This is the same origin policy protection. If the browser does not have the same origin policy protection for javascript, then some important confidential websites can be dangerous.

Has intercepted across source request: the same-origin policy prohibit read remote resources at http://127.0.0.1:8001/SendAjax/. (Cause: CORS header lacks’ access-Control-allow-origin ‘).

Cross-domain resource sharing

Cross-domain resource sharing

Allow different domains to fetch data from my server

Cross-domain problem

My server is returning data to another domain, blocked by the browser

Cross-domain request classification

  • A simple request
A request is a simple request as long as the following two conditions are met. (1) The request method is one of the following: HEAD GET POST (2) The HTTP header does not exceed the following fields: Accept accept-language content-language last-event-id content-type: Application/X-www-form-urlencoded, multipart/form-data, text/plain are limited to three valuesCopy the code
  • Non-simple request: it is a non-simple request that does not meet both of the preceding conditions.

  • The difference between simple and non-simple requests

Simple request: One request Non-simple request: two requests. The system sends one request for precheck before sending data. Only after the precheck succeeds, the system sends another request for data transmission. * About "Precheck" - How to request: If a complex request is a PUT request, the server needs to allow a certain request. If a complex request is a PUT request, the server needs to allow a certain request. Otherwise, access-Control-request-method does not pass the precheck. => If a Request header is set for a complex Request, the server must allow a Request header. Otherwise, access-Control-request-headers does not pass the precheckCopy the code

Resolve cross-domain problems

Cross-domain problem

For example: 127.0.0.1:8002 sends a request to 127.0.0.1:8000, which returns data to 127.0.0.1:8000, but is blocked by the former’s browser

Access to the XMLHttpRequest at ‘http://127.0.0.1:8000/get/’ from origin ‘http://127.0.0.1:8002’ has had been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Simple request cross-domain problem resolution

  • Solution:

No ‘access-Control-allow-origin’ header is present on the requested resource. Access-control-allow-origin = ‘domain name’ or ‘*’

Code examples:

The view class code of the server being accessed
from rest_framework.views import APIView
from rest_framework.response import Response


class TestView(APIView) :
    def get(self,request) :
        print('xxxx')
        Add 'access-Control-allow-origin ':'http://127.0.0.1:8002' to the response object of the accessed server, which means when I send data to http://127.0.0.1:8002, The other browser allows you to receive my data
        return Response('ok',headers={'Access-Control-Allow-Origin':'http://127.0.0.1:8002'})


    def post(self,request) :
        print(111111111)
        return Response('ok',headers={'Access-Control-Allow-Origin':'http://127.0.0.1:8002'})
    
Return the front-end page code and view functions for ajax requests
def index(request) :
    response = render(request,'index.html')
    return response


# Front-end code
<body>
    <button id="btn">click me</button>

    <script>
        $('#btn').click(function () {
            $.ajax({
                url:'http://127.0.0.1:8000/get/'.type:'get',
                success:function (data) {
                    console.log(data);

                }
            })
        })

    </script>
</body>
Copy the code

Non-simple request solutions

Example code:

The front-end page sends an Ajax request through POST and carries data in JSON format, which is a non-simple request.

Non-simple requests send two requests, the first a pre-check request options and the second a POST request.

[‘ access-Control-allow-headers ‘] = ‘content-type’

  • Summary: Use custom middleware to solve cross-domain request problems

You can configure the middleware in the configuration file; you do not need to configure it separately in the view function.

from django.utils.deprecation import MiddlewareMixin


class MyMiddle(MiddlewareMixin) :
    def process_response(self,request,response) :
        response['Access-Control-Allow-Origin'] = The '*'
        if request.method == 'OPTIONS':
            response['Access-Control-Allow-Headers'] = 'Content-Type'
        return response
Copy the code

A third-party plugin resolves cross-domain issues with Django-cers-headers

  • The installation

pip install django-cors-headers

  • Add it to your Settings app
INSTALLED_APPS = (
	...
	'corsheaders',...).Copy the code
  • Add to middleware
MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10.'corsheaders.middleware.CorsMiddleware'.'django.middleware.common.CommonMiddleware'. ]Copy the code
  • Configure the following code in settings.py
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
	The '*'
)
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'.)Copy the code

conclusion

The article was first published in the wechat public account Program Yuan Xiaozhuang, at the same time in nuggets.

The code word is not easy, reprint please explain the source, pass by the little friends of the lovely little finger point like and then go (╹▽╹)