ExtJS, Flask and AJAX: cross-domain request


Question

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

The problem comes 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?

1
3
5/23/2017 11:44:27 AM

Accepted Answer

Here's an excellent decorator for CORS with Flask.

http://flask.pocoo.org/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
4
10/4/2015 10:02:01 PM

You get around the problem by using CORS

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon