跨域
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/plan
复杂请求会先发出一个预请求,我们也叫预检,OPTIONS请求~~
浏览器的同源策略
跨域是因为浏览器的同源策略导致的,也就是说浏览器会阻止非同源的请求~~
非同源就是:域名不同,端口不同都属于非同源的~~~
浏览器只阻止表单以及ajax请求,并不会阻止src请求,所以我们cdn,图片等src请求都可以发~~
解决跨域
JSONP(现在已经不用了)
jsonp的实现原理是根据浏览器不阻止src请求入手来实现的
JsonP测试后端代码
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",
contentType: 'application/json', // JsonP测试时注掉
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解决跨域只能发送get请求,并且实现起来需要前后端交互比较多
添加响应头
中间件添加响应头
from django.utils.deprecation import MiddlewareMixin
class MyCors(MiddlewareMixin):
def process_response(self, request, response):
# 表示简单的跨域请求可以通过
response["Access-Control-Allow-Origin"] = "*"
# 如果是复杂请求为OPTIONS
if request.method == 'OPTIONS':
# 复杂请求会先发预检请求
# 默认ajax中的contentType: 'application/json',跨域请求不会受到阻止
response['Access-Control-Allow-Headers'] = "Content-Type"
# 当ajax中是PUT,PATCH,DELETE请求是可以通过
response['Access-Control-Allow-Methods'] = "PUT,PATCH,DELETE"
return response
注意:记得在settings.py中注册中间件
浙公网安备 33010602011771号