烧瓶和Ajax POST请求400 [英] Flask and Ajax Post requests 400

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

问题描述

我写一个小烧瓶基础的网站,我想从客户端发送的数据使用Ajax服务器。到现在为止我只用Ajax请求来从服务器获取数据。这一次,我想通过POST请求提交的数据。

这是对瓶端接收器,我减少到几乎没有记录消息,以避免这条路线的执行情况中的任何不必要的错误:

  @ app.route(/ json_submit,方法=POST])
高清submit_handler():
    #A = request.get_json(力=真)
    app.logger.log(json_submit)
    返回 {}
 

在提交Ajax请求,瓶给了我一个400错误

  127.0.0.1  -   -  [03 /月/ 2014年九时18分50秒]POST / json_submit HTTP / 1.1400  - 
 

我还可以看到在web开发控制台在浏览器

为什么瓶不叫 submit_handler 与请求提供的数据?

  VAR请求= $阿贾克斯({
    网址:/ json_submit
    键入:POST,
    数据: {
      ID:身份证,
      已知:is_known
    },
    数据类型:JSON,
  })
   .done(函数(要求){
  })
 

解决方案

如果您使用的是 Flask- WTF CSRF保护你需要或者免除您的视图或在您的AJAX POST请求的CSRF令牌了。

免除与一个装饰完成的:

  @ csrf.exempt
@ app.route(/ json_submit,方法=POST])
高清submit_handler():
    #A = request.get_json(力=真)
    app.logger.log(json_submit)
    返回 {}
 

要包括与AJAX请求令牌,插值令牌到某个地方的页面;在<元> 头或生成的JavaScript,然后设置一个 X-CSRFToken 头。当使用jQuery,使用 ajaxSetup 挂钩

使用(从烧瓶WTF CSRF文档)元标记示例:

< META NAME =CSRF令牌CONTENT ={{csrf_token()}}>

和你的JS code的地方:

VAR csrftoken = $('元[名称= CSRF令牌])。ATTR(内容) $ .ajaxSetup({     beforeSend:功能(XHR,设置){         如果(/ ^(GET!| HEAD |选项| TRACE)$ / i.test(settings.type)){             xhr.setRequestHeader(X-CSRFToken,csrftoken)         }     } })

您的处理器实际上并没有张贴JSON数据尚未;它仍然是一个普通的URL连接codeD POST (数据最终会在的Request.Form 上该瓶侧);你必须设置AJAX内容类型设置为应用程序/ JSON 和使用 JSON.stringify()实际提交JSON:

VAR请求= $阿贾克斯({    网址:/ json_submit    键入:POST,    的contentType:应用/ JSON    数据:JSON.stringify({      ID:身份证,      已知:is_known    }), })   .done(函数(要求){ })

和现在的数据也可以访问一个Python结构与<一个href="https://flask.readthedocs.org/en/latest/api/#flask.Request.get_json"><$c$c>request.get_json()方法。

数据类型:JSON,参数 $ AJAX 仅在需要时您的视图的返回的JSON(例如,您使用的<一个href="https://flask.readthedocs.org/en/latest/api/#flask.json.jsonify"><$c$c>flask.json.jsonify()产生一个JSON响应)。它可以让jQuery的知道如何处理响应。

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 {}

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 -

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

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) {
  })

解决方案

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 {}

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.

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

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

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)
        }
    }
})

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) {
})

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

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.

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

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