跨域

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

解决跨域
1.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",
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请求,并且实现起来需要前后端交互比较多。

2.添加响应头(可实现post请求)

# 中间件加响应头

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

总结:

简单请求(比较常见):方法为get,head,post,请求header里面没有自定义头,Content-Type的值为以下几种 text/plain,multipart/form-data,application/x-www-form-urlencoded。

非简单请求(比较常见):put,delect方法的ajax请求,发送json格式的ajax请求,带自定义头的ajax请求。

# 简单请求处理方案:在响应头中添加

Access-Control-Allow-Origin=“允许跨域的url”,即跨省域时,请求头Origin的值,所以一般是获取Origin的值。
Access-Control-Allow-Method=“*”,允许的方法。

# 非简单请求处理方案:在相应头中添加

Access-Control-Allow-Origin=“允许跨域的url”,即跨域时,可以获取请求头Origin的值。
Access-Control-Allow-Method=“*”,允许的方法
Access-Control-Request-Headers=“Content-Type,自定义的header的key”。

# 带cookies的跨域解决:在响应头添加

Access-Control-Allow-Credentials,="true",允许使用cookies

123

原文地址:https://www.cnblogs.com/daofaziran/p/9896760.html