跨域

 

跨域是因为浏览器的同源策略 而造成的

所以我们要告诉浏览器不让他阻止了 请求让它接收 就是在后端定义的

 你要在你的后端定义你的 跨域解决

就是告诉你的浏览器你可以让它接收

你要先定义一个中间件 因为中间件是可以设置你的 响应的返回的  可以让你的响应体来进行携带参数  那么我们就可以在中间件中设置 我们要对浏览器发送的信息 让浏览器进行接收后端发送的信息

在中间件中定义:

from django.utils.deprecation import  MiddlewareMixin

class CorsMiddleware(MiddlewareMixin):

    def process_response(self,request,response):

        response["Access-Control-Allow-Origin"] = "http://localhost:8080"   # 你的这个字典是定义的让你的请求路径可以跨域


        # 复杂模式
        if request.method == "OPTIONS":
            response["Access-Control-Allow-Methods"] = "PUT,DELETE"  # 请求方式
            response["Access-Control-Allow-Methods"] = "Content-Type"  # 验证你的请求方式

        return response

我们的复杂请求 也可以定义的在settings中:

直接定义的在settings中

CORS_METHODS = "PUT,DELETE"
# 请求方式
 CORS_HEADERS = "xxxxx,xxxxfsdf"

然后在setting中导入你的 中间件:

原文地址:https://www.cnblogs.com/zhaoyunlong/p/9446409.html