flask-CORS的尝试和解决

  因为要使用到跨域访问,就尝试了网上常见的一些解决办法,最后经过尝试发现flask有模块可以直接解决这个问题

1.安装flask-cors
pip install -U flask-ocrs
2.在配置文件app/__init__.py设置 
from flask_cors import CORS
def create_app(config_name):
app = Flask(__name__)
CORS(app) 

另外也有尝试过两种办法,但均未达到理想的效果

(1)首选方法是写了一个装饰器,然后在每个请求路由前家=加上去@allow_cross_domain ,也算是一种很麻烦的办法,但更致命的是,PUT方法时候,

  出现了错误:
XMLHttpRequest cannot load http://127.0.0.1:5000/account/status/. Response to preflight 
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'http://localhost:5001' is therefore 
not allowed access.
这时候请求变成了option, 看网上原因是CORS的规范定义,,浏览器会做一次 preflight 请求,这次请求询问服务器支持哪些方法所以,这个装饰器的办法就阵亡了
# def allow_cross_domain(fun):
#     @wraps(fun)
#     def wrapper_fun(*args, **kwargs):
#         rst = make_response(fun(*args, **kwargs))
#         
#         rst.headers['Access-Control-Allow-Origin'] = '*'
#         rst.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE'
#         allow_headers = "Referer,Accept,Origin,User-Agent"
#         rst.headers['Access-Control-Allow-Headers'] = allow_headers
#         return rst
#     return wrapper_fun

(2)然后尝试了自定义响应类,重写了Response class,但在测试的过程中,报错super()需要至少一个参数但是没有接受到入参

from flask import Flask, Response
from werkzeug.datastructures import Headers

class MyResponse(Response):
    def __init__(self, response=None, **kwargs):
        kwargs['headers'] = ''
        headers = kwargs.get('headers')
        # 跨域控制 
        origin = ('Access-Control-Allow-Origin', '*')
        methods = ('Access-Control-Allow-Methods', 'HEAD, OPTIONS, GET, POST, DELETE, PUT')
        if headers:
            headers.add(*origin)
            headers.add(*methods)
        else:
            headers = Headers([origin, methods])
        kwargs['headers'] = headers
        return super().__init__(response, **kwargs)
def create_app(): app = Flask(__name__) app.response_class = MyResponse

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值