For the following ajax
post request for Flask
(how can I use data posted from ajax in flask?):
JavaScript
x
10
10
1
$.ajax({
2
url: "http://127.0.0.1:5000/foo",
3
type: "POST",
4
contentType: "application/json",
5
data: JSON.stringify({'inputVar': 1}),
6
success: function( data ) {
7
alert( "success" + data );
8
}
9
});
10
I get a Cross Origin Resource Sharing (CORS)
error:
JavaScript
1
4
1
No 'Access-Control-Allow-Origin' header is present on the requested resource.
2
Origin 'null' is therefore not allowed access.
3
The response had HTTP status code 500.
4
I tried solving it in the two following ways, but none seems to work.
- Using Flask-CORS
This is a Flask
extension for handling CORS
that should make cross-origin AJAX possible.
- http://flask-cors.readthedocs.org/en/latest/
- How to enable CORS in flask and heroku
- Flask-cors wrapper not working when jwt auth wrapper is applied.
- Javascript – No ‘Access-Control-Allow-Origin’ header is present on the requested resource
My pythonServer.py using this solution:
JavaScript
1
15
15
1
from flask import Flask
2
from flask.ext.cors import CORS, cross_origin
3
4
app = Flask(__name__)
5
cors = CORS(app, resources={r"/foo": {"origins": "*"}})
6
app.config['CORS_HEADERS'] = 'Content-Type'
7
8
@app.route('/foo', methods=['POST','OPTIONS'])
9
@cross_origin(origin='*',headers=['Content-Type','Authorization'])
10
def foo():
11
return request.json['inputVar']
12
13
if __name__ == '__main__':
14
app.run()
15
- Using specific Flask Decorator
This is an official Flask code snippet defining a decorator that should allow CORS
on the functions it decorates.
- http://flask.pocoo.org/snippets/56/
- Python Flask cross site HTTP POST – doesn’t work for specific allowed origins
- http://chopapp.com/#351l7gc3
My pythonServer.py using this solution:
JavaScript
1
55
55
1
from flask import Flask, make_response, request, current_app
2
from datetime import timedelta
3
from functools import update_wrapper
4
5
app = Flask(__name__)
6
7
def crossdomain(origin=None, methods=None, headers=None,
8
max_age=21600, attach_to_all=True,
9
automatic_options=True):
10
if methods is not None:
11
methods = ', '.join(sorted(x.upper() for x in methods))
12
if headers is not None and not isinstance(headers, basestring):
13
headers = ', '.join(x.upper() for x in headers)
14
if not isinstance(origin, basestring):
15
origin = ', '.join(origin)
16
if isinstance(max_age, timedelta):
17
max_age = max_age.total_seconds()
18
19
def get_methods():
20
if methods is not None:
21
return methods
22
23
options_resp = current_app.make_default_options_response()
24
return options_resp.headers['allow']
25
26
def decorator(f):
27
def wrapped_function(*args, **kwargs):
28
if automatic_options and request.method == 'OPTIONS':
29
resp = current_app.make_default_options_response()
30
else:
31
resp = make_response(f(*args, **kwargs))
32
if not attach_to_all and request.method != 'OPTIONS':
33
return resp
34
35
h = resp.headers
36
37
h['Access-Control-Allow-Origin'] = origin
38
h['Access-Control-Allow-Methods'] = get_methods()
39
h['Access-Control-Max-Age'] = str(max_age)
40
if headers is not None:
41
h['Access-Control-Allow-Headers'] = headers
42
return resp
43
44
f.provide_automatic_options = False
45
return update_wrapper(wrapped_function, f)
46
return decorator
47
48
@app.route('/foo', methods=['GET','POST','OPTIONS'])
49
@crossdomain(origin="*")
50
def foo():
51
return request.json['inputVar']
52
53
if __name__ == '__main__':
54
app.run()
55
Can you please give some some indication of why that is?
Advertisement
Answer
It worked like a champ, after bit modification to your code
JavaScript
1
15
15
1
# initialization
2
app = Flask(__name__)
3
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
4
app.config['CORS_HEADERS'] = 'Content-Type'
5
6
cors = CORS(app, resources={r"/foo": {"origins": "http://localhost:port"}})
7
8
@app.route('/foo', methods=['POST'])
9
@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
10
def foo():
11
return request.json['inputVar']
12
13
if __name__ == '__main__':
14
app.run()
15
I replaced * by localhost. Since as I read in many blogs and posts, you should allow access for specific domain