Search code examples
pythonflaskextjs

Using Flask in python 2.7 to resolve the CORS issue, I need to display the response in ext.js


This is my implementation,

            full_url = url + '?' + params
            req = urllib2.Request(full_url, params)
            
            req.add_header('Content-Type', 'application/javascript')
            req.add_header('Access-Control-Allow-Origin','*')
            req.add_header('Accept', 'application/javascript')
            req.add_header('x-lang', 'en')
            req.add_header('x-app-version', '1.2.3')
            req.add_header('x-consumer-key', 'abc')
            req.add_header('x-source', 'web')
            req.add_header('x-device-id', 'abc-2501015753736970469271537365900144030')
            req.add_header('x-signature', signature)
            req.add_header('X-Content-Type-Options', 'nosniff')
            req.add_header('x-request-id', request)
            req.add_header('x-timestamp', timeStamp)

            response = urllib2.urlopen(req)
            result   = response.read()
            result   = result.decode('latin-1')
            respjson = json.loads(result)

            return respjson

Reading the output in ext.js

        var script = document.createElement("script");

        script.setAttribute("src", url);
        script.setAttribute("type", "text/javascript");
        script.setAttribute("id", trans.scriptId);
        document.getElementsByTagName("head")[0].appendChild(script);

Thank you in advance.

Error shows in the browser "was loaded even though its MIME type (“application/json”) is not a valid JavaScript MIME"

[Error in the browser][1]


Solution

  • Short Answer: Use JSONP instead of JSON in ExtJS.

    Tons of additional information

    better ways to retrieve a JSON from ExtJS

    But this was not the question I assume.

    Let's say you have your JSON and you are trying to populate a store.

    Instead of injecting the JSON into the DOM, you could use:

    Ext.StoreManager.get('storeId').load(JSON);
    // or for the store of a grid
    Ext.ComponentQuery.query('grid')[0].getStore().load(JSON);
    // or for xtype main
    Ext.first('main').getViewModel().set('initData', JSON);
    

    All these methods would get the data into an ExtJS App

    Retrieving Data

    Getting Data into ExtJS typically would be done using

    Ext.Ajax.request({
       url: full_url,
       header: ...
       success: success_fn,
       scope: this
    })
    

    Or directly in your model/store