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)
- };
- Windows.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 解决跨域只能发送 get 请求, 并且实现起来需要前后端交互比较多.
添加响应头 解决跨域错误
- 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"
- response["Access-Control-Allow-Methods"] = "DELETE, PUT, POST"
- return response
中间件加响应头
这种方式就是 告诉浏览器, 这个东西不要进行拦截.
来源: http://www.bubuko.com/infodetail-3086055.html