python 跨域

时间:2023-03-09 18:34:11
python 跨域

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请求都可以发~~

解决跨域

JSONP

jsonp的实现原理是根据浏览器不阻止src请求入手~来实现的~~

class Test(APIView):

    def get(self, request):
callback = request.query_params.get("callback", "")
ret = callback + "(" + "'success'" + ")"
return HttpResponse(ret)

JsonP实现的后端代码

<button id="btn_one">点击我向JsonP1发送请求</button>
<script>
// 测试发送请求失败 跨域不能得到数据
$('#btn_one').click(function () {
$.ajax({
url: "http://127.0.0.1:8000/jsonp1",
type: "get",
success: function (response) {
console.log(response)
}
})
}); function handlerResponse(response) {
alert(response)
}; window.onload = function () {
$("#btn_one").click(function () {
let script_ele = document.createElement("script");
script_ele.src = "http://127.0.0.1:8000/jsonp1?callback=handlerResponse";
document.body.insertBefore(script_ele, document.body.firstChild);
})
} </script> JsonP测试前端代码

JsonP测试前端代码

JsonP解决跨域只能发送get请求,并且实现起来需要前后端交互比较多。

添加响应头

from django.utils.deprecation import MiddlewareMixin

class MyCore(MiddlewareMixin):
def process_response(self, request, response):
response["Access-Control-Allow-Origin"] = "*"
if request.method == "OPTIONS":
response["Access-Control-Allow-Headers"] = "Content-Type"
response["Access-Control-Allow-Methods"] = "DELETE, PUT, POST"
return response 中间件加响应头