将json传递到发布请求时,烧瓶400错误的请求

时间:2018-06-29 16:56:58

标签: javascript python flask

我正在尝试将json从javascript传递到我的python flask后端,然后将其返回给我的javascript。

我正在粗略追踪https://www.makeuseof.com/tag/python-javascript-communicate-json/

当我按下按钮发送发布请求时,在我的工作函数中,request.is_json打印为true,但是当我尝试调用request.get_json()时,flask 400熄灭了。我相当有信心我的json格式正确,这里还缺少什么?

web.py:

#!/usr/bin/env python3

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route("/")
def output():
    return render_template("index.html", name="Joe")

@app.route('/receiver', methods = ['POST'])
def worker():

    print(request.is_json)
    data = request.get_json()

    print(data)

    return jsonify(data)

if __name__ == "__main__":
    app.run("0.0.0.0", "5000")

index.html:

{{ name }}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
    // setup some JSON to use
    var cars = [
        { "make":"Porsche", "model":"911S" }
    ];

    window.onload = function() {
        // setup the button click
        document.getElementById("theButton").onclick = function() {
            doWork()
        };
    }

    $.ajaxSetup({
      contentType: "application/json"
    });

    function doWork() {
        // ajax the JSON to the server
        $.post("receiver", cars, function(response){
            console.log(cars);
            console.log("");
            console.log(response);
        });
        // stop link reloading the page
        event.preventDefault();
    }
</script>

<p>This will send data using AJAX to Python: </p>
<a href="" id="theButton">Click Me</a>

terminal

webpage

0 个答案:

没有答案