用 Flask 解决跨域资源共享 [英] Solve Cross Origin Resource Sharing with Flask
问题描述
对于Flask
的以下ajax
post 请求(如何在flask 中使用ajax 发布的数据?):
For the following ajax
post request for Flask
(how can I use data posted from ajax in flask?):
$.ajax({
url: "http://127.0.0.1:5000/foo",
type: "POST",
contentType: "application/json",
data: JSON.stringify({'inputVar': 1}),
success: function( data ) {
alert( "success" + data );
}
});
我得到一个 跨源资源共享(CORS)
错误:
I get a Cross Origin Resource Sharing (CORS)
error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
The response had HTTP status code 500.
我尝试通过以下两种方式解决它,但似乎都不起作用.
I tried solving it in the two following ways, but none seems to work.
- 使用 Flask-CORS
这是一个用于处理 CORS
的 Flask
扩展,它应该使跨域 AJAX 成为可能.
This is a Flask
extension for handling CORS
that should make cross-origin AJAX possible.
- http://flask-cors.readthedocs.org/en/latest/
- 如何在flask和heroku中启用CORS
- Flask-cors 包装器在以下情况下不起作用应用了 jwt auth 包装器.
- Javascript - 没有访问权限"-Control-Allow-Origin' 标头存在于请求的资源上
我的 pythonServer.py 使用此解决方案:
My pythonServer.py using this solution:
from flask import Flask
from flask.ext.cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app, resources={r"/foo": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route('/foo', methods=['POST','OPTIONS'])
@cross_origin(origin='*',headers=['Content-Type','Authorization'])
def foo():
return request.json['inputVar']
if __name__ == '__main__':
app.run()
- 使用特定的 Flask 装饰器
这是一个官方 Flask 代码片段,定义了一个装饰器,该装饰器应该允许 CORS
对其装饰的函数进行处理.
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 跨站 HTTPPOST - 不适用于特定的允许来源
- http://chopapp.com/#351l7gc3
我的 pythonServer.py 使用此解决方案:
My pythonServer.py using this solution:
from flask import Flask, make_response, request, current_app
from datetime import timedelta
from functools import update_wrapper
app = Flask(__name__)
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('/foo', methods=['GET','POST','OPTIONS'])
@crossdomain(origin="*")
def foo():
return request.json['inputVar']
if __name__ == '__main__':
app.run()
你能说明为什么会这样吗?
推荐答案
在对您的代码稍加修改后,它的工作就像一个冠军
It worked like a champ, after bit modification to your code
# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/foo": {"origins": "http://localhost:port"}})
@app.route('/foo', methods=['POST'])
@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def foo():
return request.json['inputVar']
if __name__ == '__main__':
app.run()
我用 localhost 替换了 *.由于我在许多博客和帖子中读到过,您应该允许访问特定域
I replaced * by localhost. Since as I read in many blogs and posts, you should allow access for specific domain
这篇关于用 Flask 解决跨域资源共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!