带有Flask Restful的Ajax GET请求无法正常工作:无类型错误

问题描述 投票:0回答:1

我正在尝试使用Flask-restful构建简单的GET请求,并使用Ajax(带有HTML输入字段)对其进行测试。但是,出现400错误和无类型错误。但是对于Postman来说,它似乎可以工作。

这是烧瓶代码:

from flask import Flask, jsonify, request
from flask_restful import Api, Resource
import json
from api.welcome import hi_there
from flask_cors import CORS


app = Flask(__name__)
api = Api(app)
CORS(app)


class Classify(Resource):
    def get(self):
        posted_data = request.get_json(force=True)

        name = posted_data["name"]
        surname = posted_data["surname"]

        message = hi_there(name, surname)

        # Write to body dictionary
        body = {
            "welcomeMessage": message
        }

        response = {
            "statusCode": 200,
            "body": json.dumps(body),
            "headers": {
                "Access-Control-Allow-Origin": "*"
            }
        }

        return jsonify(response)


api.add_resource(Classify, '/classify')

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

Jquery代码看起来像这样:


// Endpoint URL for prediction
const exampleEndpoint = 'http://localhost:5000/classify';

$('#loader').hide();
$(document).foundation();


function sendPredictionRequest() {
    // TODO validate form
    $('#predPriceGroup').hide();
    $('#loader').show();
    $.ajax({
        type: 'GET',
        url: exampleEndpoint,
        data: JSON.stringify({
            name: $('#name').val(),
            surname: $('#surname').val()
        }),
        crossDomain: true,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function(error) {
            alert('Error while obtaining name prediction. Please check all fields and try again.');
        },
        success: function(data) {
            $('#predName').val(data.welcomeMessage);
        },
        complete: function() {
            $('#loader').hide();
            $('#predPriceGroup').show();
        }
    });
};

$('#btnPredictName').click(sendPredictionRequest);

我不断收到400错误:

{
    "message": "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)"
}

使用Postman进行测试时,我将JSON正文发送到GET请求到localhost:5000 / classify:

{
    "name": "Niels",
    "surname": "Hoogeveen"
}

结果是:

{
  "body": "{\"welcomeMessage\": \"Hi Niels Hoogeveen, how are you?!\"}",
  "headers": {
    "Access-Control-Allow-Origin": "*"
  },
  "statusCode": 200
}

我在做什么错?

jquery ajax flask flask-restful
1个回答
0
投票

问题出在您的sendPredictionRequest()方法中,它没有在api烧瓶中发送任何值。

© www.soinside.com 2019 - 2024. All rights reserved.