我正在使用 ExtJS(客户端)和 Flask(服务器)开发一个 RESTful 应用程序:客户端和服务器通过协议(protocol)链接.
当我尝试向服务器发出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 )。
服务器按如下方式处理该请求:
@app.route ("/user/update/<user_id>", methods=['GET', 'POST'])
def user_update (user_id):
return user_id
我在浏览器控制台上看到的是 OPTIONS
请求,而不是 POST
。
然后,我尝试在 80 端口上启动 Flask 应用程序,但显然这是不可能的:
app.run (host="127.0.0.1", port=80)
总而言之,如果客户端不能执行任何 AJAX 请求,我不明白客户端如何与服务器交互。
我怎样才能解决这个问题?
最佳答案
这是一个用于 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
关于javascript - ExtJS、Flask 和 AJAX : cross-domain request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12785597/