Flask和Ajax发布HTTP 400错误的请求错误 [英] Flask and Ajax Post HTTP 400 Bad Request Error

查看:106
本文介绍了Flask和Ajax发布HTTP 400错误的请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基于烧瓶的小型站点,我想使用Ajax将数据从客户端发送到服务器.到目前为止,我仅使用Ajax请求从服务器检索数据.这次我想通过POST请求提交数据.

I am writing a small flask based site and I would like to send data from the client to the server using Ajax. Until now I have only used Ajax requests to retrieve data from the server. This time I would like to submit data via POST request.

这是烧瓶侧的接收器,我将其简化为仅记录一条消息,以避免在此路由的实现中出现任何不必要的错误:

This is the receiver on the flask side, I reduced it to barely log a message to avoid any unnecessary errors within the implementation of this route:

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

提交ajax请求时,flask给了我400错误

When submitting the ajax request, flask gives me a 400 error

127.0.0.1 - - [03/Apr/2014 09:18:50] "POST /json_submit HTTP/1.1" 400 -

我还可以在浏览器的Web开发人员控制台中看到这一点

I can also see this in the web developer console in the browser

为什么烧瓶不使用请求中提供的数据调用 submit_handler ?

Why is flask not calling submit_handler with the supplied data in the request?

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

推荐答案

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

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请求中,请将令牌内插到页面中的某个位置;在< meta> 标头中或在生成的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) {
})

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

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

仅当视图返回 JSON(例如,使用href ="https://flask.readthedocs.org/en/latest/api/#flask.json.jsonify"> 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.

这篇关于Flask和Ajax发布HTTP 400错误的请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆