Skip to content

Instantly share code, notes, and snippets.

@shuson
Last active January 4, 2016 19:08
Show Gist options
  • Select an option

  • Save shuson/8664885 to your computer and use it in GitHub Desktop.

Select an option

Save shuson/8664885 to your computer and use it in GitHub Desktop.
make flask and nginx allow cross domain ajax requests from angularjs
The issue comes when make across domain(site) ajax requests, here is the situation in detail:
1, A nginx server running in localhost:8188 to response the static file request
2, A flask dynamic server running in localhost:5000 to response the ajax request using angularjs
In this situation, we have to make flask allow across site ajax request.
According to this post in flask office website: http://flask.pocoo.org/snippets/56/
and this post in serverfault:http://serverfault.com/questions/162429/how-do-i-add-access-control-allow-origin-in-nginx
1, user.html is located in Nginx server
2, app.py is running in flask server
from flask import Flask
from flask import jsonify
from crossdomain import *
app = Flask(__name__)
@app.route("/user")
@crossdomain(origin='*')
def getuser():
return jsonify({'name': "aaa", "age": 11})
if __name__ == "__main__":
app.run()
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
events {
worker_connections 1;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 8188;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Hello User</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script>
var mainApp = angular.module('mainApp',[]);
mainApp.controller('ctrl1', function($scope,$http){
$scope.user={'name':'','age':''};
$scope.getUser=function(){
$http.get('http://127.0.0.1:5000/user').success(function(data){
$scope.user=data;
})};
});
</script>
</head>
<body ng-app="mainApp">
<div id="d1" ng-controller="ctrl1">
name:{{user.name}}
<br/>
age:{{user.age}}
<br/>
<button ng-click="getUser()">Get User</button>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment