AJAX 请求 CORS Policy 错误与 Flask



我正在使用Flask来构建一个简单的后台。 我正在尝试使用 AJAX 在客户端发出一些请求,但它总是给我抛出以下错误:

访问 XMLHttpRequest at 'http://10.11.0.123/...'CORS 策略已阻止源"http://localhost:5000":对预检请求的响应未通过访问控制检查:请求的资源上不存在"访问控制-允许源"标头。

我已经尝试了几种解决方案,但没有一种奏效。我还通过以下方式使用 flask_cors 的 CORS 包:

CORS(app, resources={r"/hardware/control/1": {"origins": "http://localhost:5000"}})
app.run(host="0.0.0.0", port=5000, threaded=True)

但是,我认为这对 AJAX 请求没有影响,因为 Flask 应用程序在服务器端运行。所以这是我的 ajax 请求:

$.ajax({
url: 'http://10.11.0.123/...',
type: "GET",
contentType: 'text/plain',
headers: {
'Access-Control-Allow-Origin': '*',
},
withCredentials: true,
crossDomain: true,
success: function (result) {
console.log(result)
},
});

我知道目标服务器正在接收请求,但是我无法从服务器收到任何响应。

从 chrome 控制台分析网络请求,请求返回状态:失败和类型:xhr。

我在烧瓶中的终点是:

@system.route('/hardware/control/<int:device_id>')
def hardware_control(device_id):
device = Device.query.get(device_id)
return render_template('hardware_interaction/camera_preview.html',device=device)

我正在像这样创建应用程序:

def create_app():
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.DevelopmentConfig')
CORS(app, resources={r"/hardware/control/*": {"origins": "*"}})
with app.app_context():
return app
app = create_app()
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, threaded=True)

您可以使用它来测试它是否确实是 CORS 问题。这对我有用。

@app.after_request
def after_request(response):
header = response.headers
header['Access-Control-Allow-Origin'] = '*'
header['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
header['Access-Control-Allow-Methods'] = 'OPTIONS, HEAD, GET, POST, DELETE, PUT'
return response

标头Access-Control-Allow-Origin必须从 Flask 返回,而不是由 AJAX 请求。所以它会是这样的:

def get_content():
return "It works!", 200
@app.route('/')
def home():
content, status_code = get_content()
headers = {'Access-Control-Allow-Origin': '*'}
return content, status_code, headers

谢谢大家的帮助。我已经解决了这个问题。我正在向HTTP PTZ摄像机发出请求,这不允许我从客户端发出请求(我不知道为什么(。所以我破解了这个问题,现在我向我的服务器发出请求,我的服务器向相机发出请求。这就是我正在做的事情:

$.ajax({url: 'http://127.0.0.1:5000/teste00',
type: "GET",
success: function (result) {},
});

在服务器端:

@system.route('/teste00')
def teste():
response = requests.get('camera_url')
return response.content

有一个问题的时间,但我使用烧瓶芯

要使用 pip 安装: 点安装烧瓶烧瓶-核

请参阅 https://flask-cors.readthedocs.io/en/latest/中的文档

from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, support_credentials=True)
@app.route('/ajaxcomp')
@cross_origin(supports_credentials=True)
def ajaxcomp():
if request.is_json:
component = request.args.get('component')
comp_list = components.query.filter_by(SIGLA=componente).all()
results = components_schema.dump(comp_list)
return jsonify(results) 

对我来说工作正常。

最新更新