【问题标题】:AJAX Request CORS Policy error with FlaskFlask 的 AJAX 请求 CORS 策略错误
【发布时间】:2020-02-07 19:07:45
【问题描述】:

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

从源 'http://localhost:5000' 访问 XMLHttpRequest 在 'http://10.11.0.123/...' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-Origin ' 请求的资源上存在标头。

我已经尝试了几种解决方案,但都没有奏效。我也在使用来自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 控制台分析网络请求,请求返回 status: failed 和 Type: 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)

【问题讨论】:

  • 而不是"origins": "http://localhost:5000" 尝试"origins": "*" 并确保您访问的是resources 属性中指定的端点。正如提到的一个稀疏的答案,问题是您的服务器需要有一个 Access-Control-Allow-Origin 标头集,该标头集将在所谓的“预检”或“选项”请求中返回。与往常一样,我建议阅读文档:developer.mozilla.org/en-US/docs/Web/HTTP/CORS
  • 感谢您的回复。这没用。我已经试过了。

标签: javascript python ajax flask flask-cors


【解决方案1】:

您可以使用它来测试它实际上是一个 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

【讨论】:

  • 感谢您的回复。我已经尝试过了,但不起作用。如果这不是 CORS 问题,您认为可能是什么?
  • 您能否分享您的端点代码以及 chrome 浏览器中显示的整个错误日志。
  • 我对我的问题进行了一些修改,供您查看。谢谢
  • 我用上面的after_request 示例测试了一个示例。我还对 Ajax 进行了更改。我保留了 urltypecontentTypesuccess 并摆脱了 headerwithCredentialscrossDomain 并且它运行良好。如果您有system 蓝图并且此蓝图有url_prefix,则只需通知您可能应该将其添加到CORS 资源网址。
【解决方案2】:

标头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

【讨论】:

  • 对不起,我不明白你的 get_content() 方法是什么。
  • get_content 方法只是我必须避免编写输出的一种方法,因为我不知道它是什么。我将编辑答案以使其更容易。
  • 路由应该渲染一个模板。
【解决方案3】:

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

$.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2022-12-11
    • 2019-12-16
    • 1970-01-01
    相关资源
    最近更新 更多