Demo for Flask CORS and AngularJS while sending and receiving data



This is to demonstate the use of Flask CORS with AngularJS and jQuery while sending and receiving data.

Python server-side code:

import json, requests

from flask_cors import CORS, cross_origin

from flask import Flask, request, Response, jsonify

app = Flask(__name__)

cors = CORS(app)

app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/getresponse", methods=['POST'])

@cross_origin()

def getResponse():

    print("Content-Type: " + request.headers['Content-Type'])

    username = "There"

    if request.headers['Content-Type'] == 'text/plain':

        return "Request from client is: " + request.data

    elif(request.headers['Content-Type'] == 'application/json' or request.headers['Content-Type'] == 'application/json; charset=utf-8'):

        # For C#: request.headers['Content-Type'] == 'application/json; charset=utf-8'

        # For Python: request.headers['Content-Type'] == 'application/json'

        # For AnularJS due to the "Content-Type" headers == 'application/json'

        print("request.json: " + str(request.json))

        username = request.json['username']

  

    elif request.headers['Content-Type'] == 'application/octet-stream':

        f = open('./binary', 'wb')

        f.write(request.data)

        f.close()

        print("Binary message written!")

    

    # For JavaScript and jQuery:

    elif request.headers['Content-Type'] == 'application/x-www-form-urlencoded; charset=UTF-8':

        print(request.form['username'])

        username = request.form['username']

    else:

        return "415 Unsupported Media Type"

    

    rtnVal = "Hello %s !!" % (username)

    return rtnVal

  

if __name__ == "__main__":

    app.run(host = "0.0.0.0", port = 9000, debug = True)

Setting "debug = True" helps in faster development as it restarts the Flask server automatically on changes in the server code.

AngularJS client code (paste this code in VS Code as HTML file and press ALT+SHIFT+F for auto-formatting):

<!DOCTYPE html>

<html lang="en">

<head>

<title>Demo</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

</head>

<body ng-app="myApp">

<div class="container" ng-controller="myCtrl">

<h3>Select Username: </h3>

<div class="radio">

<label><input type="radio" name="username" ng-model="username" value="Jim">Jim Tyler</label>

</div>

<div class="radio">

<label><input type="radio" name="username" ng-model="username" value="John">John Ivy</label>

</div>

<div class="radio">

<label><input type="radio" name="username" ng-model="username" value="Jack">Jack Harper</label>

</div>

<button type="button" class="btn btn-default customLoadDataBtn" ng-click="showMessage()">Show message!</button>

</div>

</body>

<script>

angular.module('myApp', [])

.controller('myCtrl', ['$scope', '$window', '$http', function ($scope, $window, $http) {

$scope.count = 0;

$scope.showMessage = function () {

if (typeof ($scope.username) != "undefined") {

/* This is the Ajax call using jQuery:

$.ajax({

url: 'http://127.0.0.1:9000/getresponse',

method: 'POST',

data: {

"username": $scope.username

},

dataType: "text" // json OR text depending upon the output from Flask API

})

.done(function (response) {

alert(response);

})

.fail(function (jqXHR, textStatus, errorThrown) {

alert("jqXHR: " + JSON.stringify(jqXHR));

});

*/

// The following is using AngularJS:

$http({

url: "http://localhost:9000/getresponse",

data: {

"username": $scope.username

},

dataType: "json",

method: "POST",

headers: {

"Content-Type": "application/json"

}

}).then(function (response) {

console.log(response.data);

alert(response.data);

}, function (error) {

$scope.error = error;

console.log(error);

alert(JSON.parse(error));

});

} else {

$window.alert("No dataset selected.");

}

};

}]);

</script>

</html>


Notes:

When you are sending data from the Flask service to the AngularJS code and it is a dictionary, then make sure you follow these steps:

1. You are sending the response using "str()" and not "JSON.dumps()" in Python code.
2. In the AngularJS handler for getting the response, you are formatting the response before consuming it as follows:
    data = response.data.replace(/'/g, '"').replace(/nan/g, '"nan"');
    
If required you might need to do more formatting as follows:

// preserve newlines, etc - use valid JSON
data = data.replace(/\\n/g, "\\n")
    .replace(/\\'/g, "\\'")
    .replace(/\\"/g, '\\"')
    .replace(/\\&/g, "\\&")
    .replace(/\\r/g, "\\r")
    .replace(/\\t/g, "\\t")
    .replace(/\\b/g, "\\b")
    .replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
data = data.replace(/[\u0000-\u0019]+/g, "");                       

No comments:

Post a Comment