使用 Flask 解决跨源资源共享问题
2022-08-30 04:22:56
对于以下帖子请求(我如何使用从 ajax 在烧瓶中发布的数据?ajax
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)
错误:
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.
我尝试用以下两种方式解决它,但似乎没有一种奏效。
- 使用烧瓶-CORS
这是一个用于处理的扩展,应该使跨源AJAX成为可能。Flask
CORS
- http://flask-cors.readthedocs.org/en/latest/
- 如何在烧瓶和 Heroku 中启用 CORS
- Flask-cors 包装器在应用 jwt 身份验证包装器时不起作用。
- Javascript - 请求的资源上不存在“访问控制-允许-源”标头
我使用此解决方案 pythonServer.py:
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 代码片段,定义了一个装饰器,它应该允许它装饰的功能。CORS
- http://flask.pocoo.org/snippets/56/
- Python Flask 跨站点 HTTP POST - 不适用于特定允许的源
- http://chopapp.com/#351l7gc3
我使用此解决方案 pythonServer.py:
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()
您能不能给出一些说明,说明为什么会这样?