【问题标题】:Python Flask webserver not receiving JSON ajax POST requests, server returns HTTP 200 OPTIONS instead of 201 POSTPython Flask 网络服务器未接收 JSON ajax POST 请求,服务器返回 HTTP 200 OPTIONS 而不是 201 POST
【发布时间】:2016-07-22 17:21:14
【问题描述】:

我已经创建了一个 python 烧瓶网络服务器,现在只需要将它接收到的数据打印到屏幕上。我正在使用 HTML/javascript 制作带有按钮的网页。当按下按钮时,JS 应该使用 AJAX 向 python 服务器发送一个 HTTP post 请求。我得到了要连接的网页和服务器(我知道是因为我收到的是 200 代码而不是“无 JSON 对象”错误),但服务器似乎没有收到发布请求。相反,它使用 HTTP 200 OPTIONS 进行响应。我需要做什么才能将 json 对象发送到服务器?

这里是网络服务器:

from random import randint
import time
import datetime
import json
import decimal
from flask import Flask, jsonify, abort, request, make_response, url_for

app = Flask(__name__, static_url_path="")

#standard error handlers
@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify({'error': 'Bad request'}), 400)

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

@app.route('/api/data', methods=['POST'])
def post_data():
    data = json.loads(request.data)        
    print data
    print 'here'

    return jsonify({'result': 'true'}), 201



if __name__ == '__main__':
    app.run(debug=True)

这是一个简单的网页:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

    $.ajax({
        url: "http://localhost:5000/api/data",
        type: "POST",
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({apiKey: "23462"}),
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
};

</script>
</head>
<body>

<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>

</body>
</html> 

【问题讨论】:

标签: javascript python json ajax


【解决方案1】:

这可能会有所帮助:

@app.route('/api/data', methods=['POST', 'OPTIONS'])
def post_data():
    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
            'Access-Control-Max-Age': 1000,
            'Access-Control-Allow-Headers': 'origin, x-csrftoken, content-type, accept',
        }
        return '', 200, headers
    data = json.loads(request.data)
    print data
    print 'here'

    return jsonify({'result': 'true'}), 201

【讨论】:

  • 谢谢,我知道这与那些标题有关,我只是不知道如何实现它
猜你喜欢
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-09
  • 2013-07-19
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多