跨域

CORS跨域请求

CORS即Cross Origin Resource Sharing 跨域资源共享,

那么跨域请求还分为两种,一种叫简单请求,一种是复杂请求~~

简单请求

HTTP方法是下列方法之一

  HEAD, GET,POST

HTTP头信息不超出以下几种字段

  Accept, Accept-Language, Content-Language, Last-Event-ID

  Content-Type只能是下列类型中的一个

    application/x-www-from-urlencoded

    multipart/form-data

    text/plain

任何一个不满足上述要求的请求,即会被认为是复杂请求~~

复杂请求会先发出一个预请求,我们也叫预检,OPTIONS请求~~

浏览器的同源策略

跨域是因为浏览器的同源策略导致的,也就是说浏览器会阻止非同源的请求~

那什么是非同源呢~~即域名不同,端口不同都属于非同源的~~~

浏览器只阻止表单以及ajax请求,并不会阻止src请求,所以我们的cnd,图片等src请求都可以发~~

解决跨域

添加响应头
from django.utils.deprecation import MiddlewareMixin


class MyCors(MiddlewareMixin):
    def process_response(self, request, response):
        response["Access-Control-Allow-Origin"] = "*"
        if request.method == "OPTIONS":
            # 复杂请求会先发预检
            response["Access-Control-Allow-Headers"] = "Content-Type,AUTHENTICATE"  # AUTHENTICATE 把token加入进来防止前端报跨域
            response["Access-Control-Allow-Methods"] = "PUT,PATCH,DELETE"
        return response
# 中间件添加相应头
中间件添加相应头
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>

</head>
<body>
    <button id="my_button">点我发送请求</button>
    <script>
        $("#my_button").click(function () {
            $.ajax({
                url: "http://127.0.0.1:8008/cors_demo/",
                type: "put",
                contentType: "application/json",
                success: function (data) {
                    console.log(data)
                }
            })
        })

        // function handlerResponse(data) {
            // do something....
            // alert(data)
        // }



    </script>

</body>
</html>
前端测试代码
from django.shortcuts import render
from rest_framework.views import APIView
from django.http import HttpResponse

# Create your views here.


class CorsDemoView(APIView):
    def get(self, request):
        return HttpResponse("handlerResponse('ok')")
    
    def post(self, request):
        return HttpResponse("post~ok~~")
    
    def put(self, request):
        return HttpResponse("put~~ok~~")
views.py

 

posted @ 2020-10-30 10:00  断浪狂刀忆年少  阅读(103)  评论(0编辑  收藏  举报