简体   繁体   English

Flask无法处理Ajax GET请求中的JSON数据

[英]Flask can't handle json data in ajax GET request

I try to send jQuery AJAX request to my flask server : 我尝试将jQuery AJAX请求发送到我的烧瓶服务器:

$.ajax({
            type: 'GET',
            url: '/get',
            dataType: "json",
            contentType:"application/json",
            data: JSON.stringify({ subject : "gpu",
                    filter : {
                        ids: [2, 3]
                        }
                    }),
            success: function (data) {
                console.debug(data);
            }
        });

And then I wait for a response from the server. 然后,我等待服务器的响应。 Server part looks like this: 服务器部分如下所示:

@api.route('/get', methods=['GET'])
def get():
    response = None
    try:
        data = request.get_json()
        response = do_some_magic(data)
    except Exception as e:
        respond = {'state': 'error', 'data': e.message}
    finally:
        return json.dumps(respond)

So, this combination doesn't work. 因此,这种组合不起作用。 request has only args field = ImmutableMultiDict([('{"subject":"gpu","filter":{"ids":[2,3]}}', u'')]) and json field = None . request只有args字段= ImmutableMultiDict([('{"subject":"gpu","filter":{"ids":[2,3]}}', u'')])json field = None

But when in ajax request I set type: 'GET' and in flask get method methods=['GET'] , server starts to handle requests correctly. 但是,当我在ajax请求中设置type: 'GET'并在flask get方法methods=['GET'] ,服务器开始正确处理请求。

So, it would not be a real issue, but then I tried to send a GET request with postman utility. 因此,这不是真正的问题,但是后来我尝试使用邮递员实用程序发送GET请求。 It's request: 这是要求:

GET /get HTTP/1.1
Host: localhost:5000
Content-Type: application/json
cache-control: no-cache
Postman-Token: 1d94d81c-7d93-4cf6-865a-b8e3e28278c1
{
    "subject": "gpu",
    "filter": {
        "ids": [
            2,
            3
        ]
    }
}------WebKitFormBoundary7MA4YWxkTrZu0gW--

And flask code worked with methods=['GET'] . 并且flask代码与methods=['GET'] So the question is, what can cause such behaviour? 所以问题是,什么会导致这种行为?

From jQuery documentation 来自jQuery文档

data Type: PlainObject or String or Array Data to be sent to the server. 数据类型:PlainObject或String或Array要发送到服务器的数据。 It is converted to a query string, if not already a string. 如果还不是字符串,则将其转换为查询字符串。 It's appended to the url for GET-requests. 它被附加到GET请求的URL上。 See processData option to prevent this automatic processing. 请参阅processData选项以防止这种自动处理。 Object must be Key/Value pairs. 对象必须是键/值对。 If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). 如果value是一个Array,则jQuery会根据传统设置(如下所述)的值,使用相同的键序列化多个值。

If processData is set to false , it means that the data string is still appended to the URL, just without some processing. 如果processData设置为false ,则意味着data字符串仍会附加到URL,而无需进行任何处理。

This may be due to the behaviour of XMLHttpRequest.send() 这可能是由于XMLHttpRequest.send()的行为

send() accepts an optional parameter which lets you specify the request's body; send()接受一个可选参数,该参数使您可以指定请求的正文; this is primarily used for requests such as PUT. 这主要用于PUT之类的请求。 If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null. 如果请求方法是GET或HEAD,则将忽略body参数,并将请求主体设置为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM