且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flask 和 Ajax 发布 HTTP 400 错误请求错误

更新时间:2022-05-16 07:58:10

如果您使用的是 Flask-WTF CSRF 保护您需要在 AJAX POST 请求中免除您的视图或包含 CSRF 令牌.

If you are using the Flask-WTF CSRF protection you'll need to either exempt your view or include the CSRF token in your AJAX POST request too.

免除是通过装饰器完成的:

Exempting is done with a decorator:

@csrf.exempt
@app.route("/json_submit", methods=["POST"])
def submit_handler():
    # a = request.get_json(force=True)
    app.logger.log("json_submit")
    return {}

要将令牌包含在 AJAX 请求中,请将令牌插入页面中的某处;在 标头或生成的 JavaScript 中,然后设置 X-CSRFToken 标头.使用 jQuery 时,请使用 ajaxSetup 钩子.

To include the token with AJAX requests, interpolate the token into the page somewhere; in a <meta> header or in generated JavaScript, then set a X-CSRFToken header. When using jQuery, use the ajaxSetup hook.

使用元标记的示例(来自 Flask-WTF CSRF 文档):

Example using a meta tag (from the Flask-WTF CSRF documentation):

<meta name="csrf-token" content="{{ csrf_token() }}">

在你的 JS 代码中:

and in your JS code somewhere:

var csrftoken = $('meta[name=csrf-token]').attr('content')

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken)
        }
    }
})

您的处理程序实际上还没有发布 JSON 数据;它仍然是一个常规的 url 编码的 POST(数据将在 Flask 端的 request.form 中结束);您必须将 AJAX 内容类型设置为 application/json 并使用 JSON.stringify() 来实际提交 JSON:

Your handler doesn't actually post JSON data yet; it is still a regular url-encoded POST (the data will end up in request.form on the Flask side); you'd have to set the AJAX content type to application/json and use JSON.stringify() to actually submit JSON:

var request = $.ajax({
   url: "/json_submit",
   type: "POST",
   contentType: "application/json",
   data: JSON.stringify({
     id: id, 
     known: is_known
   }),  
})  
  .done( function (request) {
})

现在可以使用请求作为Python结构访问数据.get_json() 方法.

and now the data can be accessed as a Python structure with the request.get_json() method.

dataType: "json", 参数 $.ajax 仅在您的视图 返回 JSON 时才需要(例如,您使用了 flask.json.jsonify() 生成 JSON 响应).它让 jQuery 知道如何处理响应.

The dataType: "json", parameter to $.ajax is only needed when your view returns JSON (e.g. you used flask.json.jsonify() to produce a JSON response). It lets jQuery know how to process the response.