0

I am using flask to wrote a small website use the Postman to send the post request

app.py

@app.route('/index', methods=['GET', 'POST'])
def index():
    if session["logged_in"]:
        return render_template('index.html')
    else:
        return redirect(url_for('login'))

@app.route('/get_msg', methods = ['POST'])
def get_msg():
    time_toshow = request.get_json(force = True)
    return time_toshow

index.html(main part)

    <script>
        $(document).ready(function(){
            $.ajax({
                url: "{{url_for('get_msg')}}",
                type: 'post',
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    $('#shown').html(data);
                    console.log(data);
                },
            });
        })
    </script>
</head>
<body>
    <h1 id='shown' class='blackshadow' style="font-size: 80px">Good</h1>
</body>

The webpage never update after sending a post request via Postman the post request I send to http://127.0.0.1:5000/get_msg is:

{"AbnormalTime": "5000"}

The console also logs nothing

Yiling Liu
  • 666
  • 1
  • 6
  • 21

1 Answers1

1

Try this:

$.ajax({
    url: "{{url_for('get_msg')}}",
    type: 'post',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(time_toshow),
    success: function (data) {
        $('#shown').html(JSON.stringify(data));
        console.log(data);
    },
});

Note the JSON.stringify(), both in the success function and when passing the data.

If you don't use JSON.stringify(), your JSON is converted to AbnormalTime=5000 instead of {"AbnormalTime": "5000"}, so the server returns a 400 error (bad request). See here.

FoolsWisdom
  • 821
  • 4
  • 6