• Django 跨域访问POST请求需预先发送option请求问题处理方案


    跨域访问POST请求需预先发送option请求问题处理方案

     

     

    By:授客 QQ:103355122

     

    实践环境

    Win 10

     

    Python 3.5.4

     

    Django-2.0.13.tar.gz

    官方下载地址:

    https://www.djangoproject.com/download/2.0.13/tarball/

     

    问题描述

    使用POST请求访问Django后端API时自动先发送option请求,然后才执行POST请求

     

    原因分析

    跨域资源共享(CORS)机制导致。

     

    浏览器将CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。

    只要同时满足以下两大条件,就属于简单请求,否则就是非简单请求。

    1、请求方法是以下三种方法之一:

    HEAD

    GET

    POST  

     

    2、HTTP的头信息不超出以下几种字段:

    Accept

    Accept-Language

    Content-Language

    Last-Event-ID

    Content-Type(其值只限于application/x-www-form-urlencoded、multipart/form-data、text/plain)

     

    当请求存在跨域资源共享(CORS),并且是非简单请求,就会触发CORS的预检请求(preflight);"预检"请求用的请求方法是OPTIONS,如果请求OK,才会再次发送目标操作请求。

     

    实际开发过程中,后台采用token检验机制,前台发送请求必须将token放到Request Header中,那么就需要传输自定义Header信息、或则请求头中的Content-Type设置为"application/json",就会形成非简单请求。 但是很多时候,我们并不希望浏览器这么做,重复的请求,一方面是增加服务器压力,另一方面,相当于增加了请求响应时间。 

     

    解决方法 

    一种比较合适的解决方法就是增加响应头“Access-Control-Max-Age”来控制浏览器在多长时间内(单位为秒)无需在请求时发送预检请求,从而减少不必要的预检请求。

     

    中间件代码如下:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
     
    __author__ = '授客'
     
    from django.utils.deprecation import MiddlewareMixin
     
    class PublicAccessControlMiddleware(MiddlewareMixin):
        def process_request(self, request):
            pass
     
        def process_response(self, request, response):
            response['Access-Control-Max-Age'] = 86400 #3600*24h = 86400秒,即告诉浏览器,缓存预检结果24小时,即针对同一URL请求,发送第一个OPTION请求往后24小时内不再发送OPTION请求。
        return response
    

      

     

    参考链接

    https://juejin.im/post/5c889e136fb9a049d37ff768

     

  • 相关阅读:
    241. Different Ways to Add Parentheses
    332. Reconstruct Itinerary
    [LeetCode] 19. Remove Nth Node From End of List Java
    [LeetCode] 16. 3Sum Closest Java
    [LeetCode] 15. 3Sum Java
    [LeetCode] 11. Container With Most Water Java
    [LeetCode] 4. Median of Two Sorted Arrays
    [LeetCode] 3.Longest Substring Without Repeating Characters
    [LeetCode] 50. Pow(x, n) Java
    [LeetCode] 45. Jump Game II Java
  • 原文地址:https://www.cnblogs.com/shouke/p/14170298.html
Copyright © 2020-2023  润新知