Flask and Ajax Post HTTP/1.1" 400

Flask and Ajax Post HTTP/1.1" 400

太感谢https://stackoverflow.com/了,作者真的和牛,能解决问题

一下是转载的,mark一下,为了帮助更多的人。

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可以不加

@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 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):

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.

你可能感兴趣的:(Django)