【问题标题】:Ajax call to Flask Rest API does not get JSON对 Flask Rest API 的 Ajax 调用未获取 JSON
【发布时间】:2018-07-18 14:19:40
【问题描述】:

我使用 Flask 对我的 REST API 进行了以下 ajax 调用:

$.ajax({
    type: "POST",
    cache: false,
    url: "/addEvent",
    dataType: "json",
    data: JSON.stringify({
        "event_id": "e-123"
        }),
    success: function(response, status, xhr) {
        var ct = xhr.getResponseHeader("content-type") || "";        
        if ( xhr.status == 200 ) {
            console.log("Event created.");
        }
        else {
            alert("Error! status: " + xhr.status)
        }
    },
    error: function(xhr, exception) {
        console.log("error > xhr.status:" + xhr.status);
        console.log("error > exception: " + exception);
    },
    complete: function(response, status, xhr) {
        console.log("Finished!");
    }
});

我的 Flask REST API app.py 文件包含以下内容:

from flask import Flask, request
def addEvent():
    request_data = request.get_json() 

但是,'request_data' 是 None,而 request.get_data() 包含 b'{"event_id":"e-123"}'

我的 ajax 调用有什么问题吗?

【问题讨论】:

    标签: json ajax flask


    【解决方案1】:

    您正在向 Flask REST API 发送一个字符串。

    尝试更改 ajax 调用中的数据字段:

    data: JSON.stringify({
        "event_id": "e-123"
        })
    

    data: {
        "event_id": "e-123"
        }
    

    【讨论】:

    • 这不会改变任何东西。 request.get_json() 仍然是 None 而 request.get_data() 包含 b'event_id=e-123'
    【解决方案2】:

    在您的 AJAX 请求中添加 contentType: 'application/json'

    $.ajax({
        type: "POST",
        cache: false,
        url: "/addEvent",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: ...
    

    【讨论】:

      猜你喜欢
      • 2018-02-06
      • 2020-07-14
      • 1970-01-01
      • 2014-04-08
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 2015-04-03
      相关资源
      最近更新 更多