javascript - ExtJS, Flask and AJAX: cross-domain request - Stack Overflow

I'm developing a RESTful application with ExtJS (client) and Flask (server): client and server are

I'm developing a RESTful application with ExtJS (client) and Flask (server): client and server are linked by a protocol.

The problem es when I try to do an AJAX request to the server, like this:

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
    }
});

With the above request, the client is trying to update the user information. Unfortunately, this is a cross-domain request (details).

The server handles that request as follows:

@app.route ("/user/update/<user_id>", methods=['GET', 'POST'])
def user_update (user_id):
  return user_id

What I see on the browser console is an OPTIONS request instead of POST. Then, I tried to start the Flask application on the 80 port but it's not possible, obviously:

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

In conclusion, I don't understand how the client can interact with the server if it cannot do any AJAX request.

How can I get around this problem?

I'm developing a RESTful application with ExtJS (client) and Flask (server): client and server are linked by a protocol.

The problem es when I try to do an AJAX request to the server, like this:

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
    }
});

With the above request, the client is trying to update the user information. Unfortunately, this is a cross-domain request (details).

The server handles that request as follows:

@app.route ("/user/update/<user_id>", methods=['GET', 'POST'])
def user_update (user_id):
  return user_id

What I see on the browser console is an OPTIONS request instead of POST. Then, I tried to start the Flask application on the 80 port but it's not possible, obviously:

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

In conclusion, I don't understand how the client can interact with the server if it cannot do any AJAX request.

How can I get around this problem?

Share Improve this question edited May 23, 2017 at 11:44 CommunityBot 11 silver badge asked Oct 8, 2012 at 16:23 WilkWilk 8,14310 gold badges47 silver badges71 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Here's an excellent decorator for CORS with Flask.

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

Here's the code for posterity if the link goes dead:

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

You get around the problem by using CORS

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

The module Flask-CORS makes it extremely simple to perform cross-domain requests:

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

See also: https://pypi.python/pypi/Flask-Cors

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745367657a4624654.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信