0

I am trying to send the data from Flask to AngularJS.

Server

@app.route("/data")
def getDataFromDB():
      cur.execute("select * from employee")
      rows = cur.fetchall()
      columns = [desc[0] for desc in cur.description]
      result = []
      for row in rows:
          row = dict(zip(columns, row))
          json_row=json.dumps(row)
          result.append(json_row)
          json_response=json.dumps(result)
     response=Response(json_response,content_type='application/json; charset=utf-8')
     response.headers.add('content-length',len(json_response))
     response.status_code=200
     return response

Client

maincontroller.js

  var app=angular.module('myApp',[]);
  app.controller("MainController", function($scope,$http){

  var done=function(resp){

  $scope.lists=resp.data;
  };
  var fail=function(err){

  };

 $http.get('http://10.62.XX.XX:8083/data')
 .then(done,fail);

});

index.html

<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"     
type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src="maincontroller.js" type="text/javascript"></script>

</head>
<body ng-app="myApp">

<div id='content'  ng-controller='MainController'>

 <div>
    <ul>
        <li ng-repeat='ele in list'>{{ele}}</li>
    </ul>
 </div>

 </div>
 </body>
 </html>

Now, when I access the above code using jsbin.com, I can see my api getting called but nothing is visible on the output screen in jsbin. It is blank. But when I put the same code in eclipse, I see no api call happening. Do I need to do something more to make angularJS work? I just open the index.html with web browser.

6
  • Do you ever load mainController.js on the page? Commented Jul 15, 2014 at 20:24
  • <head> <title>Learning AngularJS</title> <script src="ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="model.css"> <script src="app.js" type="text/javascript"></script> <script src="maincontroller.js" type="text/javascript"></script> </head> Commented Jul 15, 2014 at 20:33
  • And when you look at the network traffic in your browser are app.js and maincontroller.js being found or are they 404s? Commented Jul 15, 2014 at 20:42
  • i donot see 404 but a blank page. Commented Jul 15, 2014 at 20:45
  • Yes, but when you hit 10.62.XX.XX:8083/app.js do you get JavaScript or a 404? Commented Jul 15, 2014 at 20:48

1 Answer 1

2

If the IP is not your local machine you need to setup CORS on the server. I am not familiar with Flask but it looks like there is a package that handles this. I also found a function that sets up CORS for Flask.

from datetime import timedelta  
from flask import Flask, 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


@app.route('/')
@crossdomain(origin='*')
def landing():  
    return jsonify(i_am_a='cross domain resource!')

if __name__ == '__main__':  
    app.run(host='0.0.0.0', port=8080)
Sign up to request clarification or add additional context in comments.

11 Comments

+1 for knowing the problem before the OP even made it clear that he was using different origins.
thanks for the information Andy. so in the server : @app.route("/data") @cross_origin() def getDataFromDB(): it does not seem to work for me. Am I missing something?
so now I have ported my code to the same machine. so have same IPs. still not happening. also when i do 10.62.XX.XX:8083/app.js, I am getting 404.
You will have to use developer tools or an http proxy like fiddler to determine whether or not your server is sending back the correct headers (see the Wikipedia link). Also use a more recent version of angular if you can.
I have installed the latest version of Angular on eclipse. My network doesnot allow install of fiddler. getting no idea what is getting missed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.