CORS即Cross Origin Resource Sharing 跨域資源共享,那麼跨域請求還分爲兩種,一種叫簡單請求,一種是複雜請求css
簡單請求html
HTTP方法是下列方法之一vue
HEAD, GET,POSTios
HTTP頭信息不超出如下幾種字段ajax
Accept, Accept-Language, Content-Language, Last-Event-IDnpm
Content-Type只能是下列類型中的一個django
application/x-www-from-urlencodedjson
multipart/form-dataaxios
text/plain後端
任何一個不知足上述要求的請求,即會被認爲是複雜請求
複雜請求會先發出一個預請求,咱們也叫預檢,OPTIONS請求
瀏覽器的同源策略
跨域是由於瀏覽器的同源策略致使的,也就是說瀏覽器會阻止非同源的請求
非同源即域名不一樣,端口不一樣都屬於非同源的
瀏覽器只阻止表單以及ajax請求,並不會阻止src請求,因此咱們的cdn,圖片等src請求均可以發
jsonp的實現原理是根據瀏覽器不阻止src請求入手來實現的
from django.shortcuts import render from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response # Create your views here. class DemoView(APIView): def get(self, request): res = "handlerResponse('跨域測試')" return HttpResponse(res) def put(self, request): return Response("put接口測試") def post(self, request): return Response("POST接口測試")
JsonP解決跨域只能發送get請求,而且實現起來須要先後端交互比較多。
JsonP解決跨域
jsonp 用 script 的方式去請求,只能經過get請求數據
<script> function handlerResponse(data) { console.log(data) } </script> <script src="http://127.0.0.1:8000/demo/"></script>
告訴瀏覽器不要攔截來解決跨域
中間件 middlewares.py
from django.utils.deprecation import MiddlewareMixin class MyCors(MiddlewareMixin): def process_response(self, request, response): response["Access-Control-Allow-Origin"] = "*" # 任何跨域都不攔截 if request.method == "OPTIONS": # 預檢,OPTIONS請求 response["Access-Control-Allow-Methods"] = "PUT, DELETE" response["Access-Control-Allow-Headers"] = "content-type" return response
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script> <script> function handlerResponse(data) { console.log(data) } </script> <script src="http://127.0.0.1:8000/demo/"></script> </head> <body> <div id="app"> </div> <script> const app = new Vue({ el: "#app", mounted(){ axios.request({ url: "http://127.0.0.1:8000/demo/", method: "PUT", data: { "name": "Alex" } }).then(function (data) { console.log(data) }) } }) </script> </body> </html>