Python Flask Web服务器未接收到JSON ajax POST请求,服务器返回HTTP 200 OPTION

Python Flask webserver not receiving JSON ajax POST requests, server returns HTTP 200 OPTIONS instead of 201 POST

本文关键字:服务器 请求 POST 返回 HTTP OPTION ajax JSON Web Flask Python      更新时间:2023-11-30

我创建了一个python flask web服务器,到目前为止,它只需要将接收到的数据打印到屏幕上。我正在使用HTML/javascript制作一个带有按钮的网页。当按下按钮时,JS应该使用AJAX向python服务器发送一个HTTP post请求。我让网页和服务器连接(我知道,因为我收到的是200代码,而不是"无JSON对象"错误),但服务器似乎没有收到post请求。相反,它使用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> 

这可能会有所帮助:

@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