CORS

 COURSES:

    Concept: Because browsers have the same origin policy, in order to solve cross-domain requests, there are two ways: 1. JSONP generates a script dynamically, initiates a request through ajax and obtains the corresponding data

        2. The use of CORS requires both browser and server support. Currently, all browsers support this function. The entire CORS communication process is completed automatically by the browser and does not require user participation.

        Once the browser discovers that the AJAX request is cross-origin, it will automatically add some additional header information. Therefore, the key to implementing CORS communication is the server. As long as the server implements the CORS interface, cross-domain communication is possible.

    Two kinds of requests:

1. Simple request:

    Request method: HEAD, GET, POST

    HTTP header information:

        .Accept

        .Accept-Language

        .Content-Language

        .Last-Event-ID

        .Content-Type is limited to three values: application/x-www-form-urlencoded, multipart/form-data, tecx/plain

   Request process:

   When the browser finds that this cross-origin ajax is a simple request, it will automatically add an Origin field to the header information, which is used to indicate which source (protocol + domain name + port) the request came from.

   Based on this value, the server decides whether to agree to the request. If it is within the permitted range, the server will respond with several additional header fields.

   1.Access-Control-Allow-Origin: http://api.bob.com #This field is required, * indicates that requests from any domain name are accepted

   2.Access-Control-Allow-Credentials: true #Optional indicates whether cookies can be sent

   3.Access-Control-Expose-Headers: FooBar #getResponseHeader() method can only get other fields except 6 basic fields

   4.withCredentials:

       If you want to send cookies to the server, on the one hand, the server needs to agree to Access-Control-Allow-Credentials: true,

       On the other hand, the developer must turn on the withCredentials property in the Ajax request var xhr = new XMLHttpRequest();xhr.withCredentials = true

       Access-Control-Allow-Origin cannot be set to * if cookies need to be sent

   A website:

       <input type="button" value="Get user data" onclick="getUsers()">

 

       <script src="jquery-1.12.4.min.js"></script>

       <script>

           function getUsers() {

               $.ajax({

                   url: 'http://127.0.0.1:8000/users/',

                   type:'GET',

                   success: function (ret) {

                       console.log (ret)

                   }

               })

           }

       </script>

  

   Service provider:

       class UsersView(views.APIView):

           def get(self,request,*args,**kwargs):

           ret = {

               'code':1000,

               'data':'Chen Taizhang'

           }

           response = JsonResponse(ret)

           response['Access-Control-Allow-Origin'] = "*"

           return response

         

2. Non-simple request:

    Request method: PUT, DELETE

    Header information: The type of the Content-Type field is application/json

    Request process:

  1. Before the official communication, add an HTTP query request, first ask the server, whether the domain name of the current webpage is in the server's permission list, and whether the header information can be used, only after obtaining permission

      The browser will issue a formal XMLHttpRequest request. The method of the preflight request is option, indicating that the request is used to ask. The keyword origin in the header information indicates which source it comes from.

      It also contains two other special fields, 1.Access-Control-Request-Method lists those methods that CORS requests will use, and 2.Access-Control-Request-Headers lists additional header information sent.

  2. After the server receives the preflight, it checks each field to confirm that cross-origin requests are allowed, and then it can respond. If the server does not agree with the preflight request, it will return a normal HTTP response, but it does not contain CORS-related header information.

      The browser decides that the server does not agree with the preflight and triggers an error.

      The server returns CORS related fields:

          1.Access-Control-Allow-Methods: GET, POST, PUT #Indicates all cross-domain request methods supported by the server

          2.Access-Control-Allow-Headers: X-Custom-Header # Indicates all header fields supported by the server

          3.Access-Control-Allow-Credentials: true #Indicates that cookies can be carried

          4.Access-Control-Max-Age: 1728000 #Indicate the valid time of the pre-check, during this period, it is not necessary to send another pre-check

  3. After the server passes the pre-check request, in the valid area of ​​the pre-check, each CORS request follows the simple request method.

          def options(self, request, *args, **kwargs):

              # self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")

              # self.set_header('Access-Control-Allow-Headers', "k1,k2")

              # self.set_header('Access-Control-Allow-Methods', "PUT,DELETE")

              # self.set_header('Access-Control-Max-Age', 10)

 

              response = HttpResponse()

              response['Access-Control-Allow-Origin'] = '*'

              response['Access-Control-Allow-Headers'] = 'h1'

              # response['Access-Control-Allow-Methods'] = 'PUT'

              return response

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325134326&siteId=291194637