ExtJS、Flask和AJAX:跨域需求

2024-05-23 18:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用ExtJS(客户机)和Flask开发一个RESTful应用程序:客户机和服务器通过协议连接。在

当我试图对服务器执行AJAX请求时,问题就出现了,如下所示:

Ext.Ajax.request ({
    url: 'http://localhost:5000/user/update/' + userId ,
    method: 'POST' ,
    xmlData: xmlUser ,
    disableCaching: false ,
    headers: {
        'Content-Type': 'application/xml'
    } ,
    success: function (res) {
        // something here
    } ,
    failure: function (res) {
        // something here
    }
});

通过上述请求,客户端正在尝试更新用户信息。 不幸的是,这是一个跨域请求(details)。

服务器按如下方式处理该请求:

^{pr2}$

我在浏览器控制台上看到的是一个OPTIONS请求,而不是POST。 然后,我试图在80端口上启动烧瓶应用程序,但显然不可能:

app.run (host="127.0.0.1", port=80)

总之,我不明白如果客户端不能执行任何AJAX请求,它如何与服务器交互。在

我怎样才能避开这个问题?在


Tags: 服务器restful应用程序协议客户端flask客户机here
3条回答

模块Flask-CORS使跨域请求的执行变得非常简单:

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

另请参见:https://pypi.python.org/pypi/Flask-Cors

这是一个很好的装饰用烧瓶。在

http://flask.pocoo.org/snippets/56/

如果链接死了,给后人的代码是:

from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper


def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            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)
            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

你可以通过使用CORS来解决这个问题

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

相关问题 更多 >