跨域(my)
Posted ls13691357174
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了跨域(my)相关的知识,希望对你有一定的参考价值。
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请求都可以发~~
Ajax跨域现象
urls.py:
from django.conf.urls import url from django.contrib import admin from .views import jsonp1 urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^jsonp1‘,jsonp1) ]
views.py
from django.http import HttpResponse def jsonp1(request): return HttpResponse("hello")
创建 .html 当做前端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <body> <button id="btn">点我向后端发送数据</button> <script> $("#btn").click(function(){ $.ajax({ url:"http://127.0.0.1:8000/jsonP1" , //后端的路由地址 success:function(data){ console.log(data) } }) }) </script> </body> </html>
解决跨域
JSONP
jsonp的实现原理是根据浏览器不阻止src请求入手~来实现的~~
urls.py:
from django.conf.urls import url from django.contrib import admin from .views import jsonp1 urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^jsonp1‘,jsonp1) ]
views.py:
from django.http import HttpResponse def jsonp1(request): ret = "handlerResponse(‘hello555‘)" return HttpResponse(ret)
jsonp2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <body> <button id="btn">点我向后端发送数据</button> <script> // 页面加载完成执行的方法 window.onload = function () { let ele = document.createElement("script"); // 给标签加src属性 ele.src = "http://127.0.0.1:8001/jsonp1"; // 把标签放到页面上 document.body.insertBefore(ele, null) } function handlerResponse(data) { alert(data) } </script> </body> </html>
===========================
views.py:
from django.http import HttpResponse def jsonp1(request): callback = request.GET.get("callback","")#获取callback # ret = "handlerResponse(‘hello555‘)" ret = callback + "(‘hello‘)" return HttpResponse(ret)
jsonp2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <body> <button id="btn">点我向后端发送数据</button> <script> function handlerResponse(data) { alert(data) } // 页面加载完成执行的方法 window.onload = function () { let ele = document.createElement("script"); // 给标签加src属性 ele.src = "http://127.0.0.1:8001/jsonp1?callback=handlerResponse"; // 把标签放到页面上 document.body.insertBefore(ele, null) } </script> </body> </html>
添加响应头
settings.py注释中间件csrf
注册中间件:‘middlewares.MyCors‘
urls.py:
from django.conf.urls import url from django.contrib import admin from .views import jsonp1 urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^jsonp1‘,jsonp1) ]
jsonp2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <body> <button id="btn">点我向后端发送数据</button> <script> $("#btn").click(function () { $.ajax({ url: "http://127.0.0.1:8001/jsonp1", type: "post", contentType: "application/json", data: {"name": "liangshuang"}, success: function (data) { console.log(data) } }) }) </script> </body> </html>
views.py
from django.http import HttpResponse def jsonp1(request): callback = request.GET.get("callback","")#获取callback # ret = "handlerResponse(‘hello555‘)" ret = callback + "(‘hello‘)" print(ret) return HttpResponse(ret)
在项目下创建middlewares.py定义中间件
# -*- coding: utf-8 -*- # __author__ = "maple" from django.middleware.security import SecurityMiddleware 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": response["Access-Control-Allow-Headers"] = "Content-Type" response["Access-Control-Allow-Methods"] = "POST, PUT, PATCH, DELETE" return response
以上是关于跨域(my)的主要内容,如果未能解决你的问题,请参考以下文章