zoukankan      html  css  js  c++  java
  • 「Django」rest_framework学习系列-API访问跨域问题

    #以中间件方式解决API数据访问跨域问题
    1.API下新建文件夹下写PY文件
    a.引入内置类继承:

    from django.middleware.common import MiddlewareMixin
    
    class CORSMiddleware(MiddlewareMixin):
        def process_response(self,request,response):
            #添加响应头
            #允许你的域名来获取我的数据,'*'也可以单独设置
            response['Access-Control-Allow-Origin'] = '*'
    
            #允许携带Content-Type请求头
            response['Access-Control-Allow-Headers'] = 'Content-Type'
    
            #如果PUT或者别的请求形式报错
            response['Access-Control-Allow-Methods'] = 'put,'
    
            return response
    View Code

    b.重写继承类:

    可以引入,也可以如下重写方法
    class MiddlewareMixin:
        def __init__(self, get_response=None):
            self.get_response = get_response
            super().__init__()
    
        def __call__(self, request):
            response = None
            if hasattr(self, 'process_request'):
                response = self.process_request(request)
                response = response or self.get_response(request)
            if hasattr(self, 'process_response'):
                response = self.process_response(request, response)
            return response
    
    class CORSMiddleware(MiddlewareMixin):
        def process_response(self,request,response):
        #添加响应头
        #允许你的域名来获取我的数据,'*'也可以单独设置
        response['Access-Control-Allow-Origin'] = '*'
        #允许携带Content-Type请求头,如果允许别的请求头加入,写在后面,如k1
        response['Access-Control-Allow-Headers'] = 'Content-Type,k1'
    
        return response    
    View Code

    2.settings中间件添加

    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'middleware.CorsMiddleware.CORSMiddleware'#引入处理跨域的类
    ]
    View Code
  • 相关阅读:
    下班的时候收到两封Mail
    图解SSIS监视文件夹并自动导入数据
    用SqlDependency类为SQL2005查询提供更改通知
    一句话理解ref object的意义
    开源Mono框架将C#编程带到iPhone、Android和Wii
    div css 图片和文字上下居中对齐
    js 表单验证思路
    jquery 表单验证插件
    PHP开源AJAX框架
    Hello China V1.5 源码下载地址
  • 原文地址:https://www.cnblogs.com/wrxblog/p/10416291.html
Copyright © 2011-2022 走看看