Javascript

Javascript,第1张

Javascript

我使Javascript与Flask一起使用,并在可接受的方法列表中添加了“ OPTIONS”。装饰器应在路线装饰器下方使用,如下所示:

@app.route('/login', methods=['POST', 'OPTIONS'])@crossdomain(origin='*')def login()    ...

编辑: 链接似乎已断开。这是我使用的装饰器。

from datetime import timedeltafrom flask import make_response, request, current_appfrom functools import update_wrapperdef crossdomain(origin=None, methods=None, headers=None, max_age=21600,     attach_to_all=True, automatic_options=True):    """Decorator function that allows crossdomain requests.      Courtesy of      https://blog.skyred.fi/articles/better-crossdomain-snippet-for-flask.html    """    if methods is not None:        methods = ', '.join(sorted(x.upper() for x in methods))    # use str instead of basestring if using Python 3.x    if headers is not None and not isinstance(headers, basestring):        headers = ', '.join(x.upper() for x in headers)    # use str instead of basestring if using Python 3.x    if not isinstance(origin, basestring):        origin = ', '.join(origin)    if isinstance(max_age, timedelta):        max_age = max_age.total_seconds()    def get_methods():        """ Determines which methods are allowed        """        if methods is not None: return methods        options_resp = current_app.make_default_options_response()        return options_resp.headers['allow']    def decorator(f):        """The decorator function        """        def wrapped_function(*args, **kwargs): """Caries out the actual cross domain pre """ if automatic_options and request.method == 'OPTIONS':     resp = current_app.make_default_options_response() else:     resp = make_response(f(*args, **kwargs)) if not attach_to_all and request.method != 'OPTIONS':     return resp h = resp.headers h['Access-Control-Allow-Origin'] = origin h['Access-Control-Allow-Methods'] = get_methods() h['Access-Control-Max-Age'] = str(max_age) h['Access-Control-Allow-Credentials'] = 'true' h['Access-Control-Allow-Headers'] =      "Origin, X-Requested-With, Content-Type, Accept, Authorization" if headers is not None:     h['Access-Control-Allow-Headers'] = headers return resp        f.provide_automatic_options = False        return update_wrapper(wrapped_function, f)    return decorator


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4903828.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存