Flask 和 Ajax 发布 HTTP 400 错误请求错误 [英] Flask and Ajax Post HTTP 400 Bad Request Error
问题描述
我正在编写一个基于烧瓶的小站点,我想使用 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.
这是flask端的接收器,我将其简化为几乎不记录消息以避免在此路由的实现中出现任何不必要的错误:
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
为什么flask没有使用请求中提供的数据调用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 保护您需要在 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.
这篇关于Flask 和 Ajax 发布 HTTP 400 错误请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!