我的 Flask API 响应中的冗余服务器信息



我正在python Flask应用程序中编写一个API。

@app.route('/result', method=['GET'])
def result():
  data = {}
  data['age'] = 18
  data['name'] = 'Jack'
  return jsonify(result=data)

编辑:我使用Ajax调用API,

$.ajax({
    url: "/result",
    type: "GET",
    dataType: "json",
    success: function (data) {
      data = eval(data);
      // other actions
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  }
)

为什么有时当我调用此 API 时,API 响应正文中添加了一些冗余服务器信息,而我无法将其解析为有效的 json。喜欢

预期成果:

{
  "result": {
    "age": 18,
    "name": "Jack"
  }
}

实际结果:

Content-Type: application/json
Content-Length: 187252
Server: Werkzeug/0.12.2 Python/2.7.14
{"result":{"age":18, "name":"Jack"}}

出于什么原因会发生这种情况,任何人都可以提供一些可能的想法吗?

只需要返回json数据和前端告诉ajax contentType是json!

return jsonify(data)

这是我的例子:

后端

@main.route('/api/data')
def foo():
    return jsonify({"bar": True})

前端(JavaScript ajax(

function ajax(method, url, data, callback) {
    var obj = {
        type: method,
        url: window.location.origin + url,
        contentType: "application/json; charset=utf-8",
        success: function (a) {
            callback(a);
        }, error: function (err) {
            if ((err.responseJSON).constructor == Object)
                Object.keys(err.responseJSON).length || (err.responseJSON = {'error': err.statusText});
            else if ((err.responseJSON).constructor == Array)
                err.responseJSON.length || (err.responseJSON = {'error': err.statusText});
            callback(err.responseJSON);
        }
    };
    data && (obj.data = JSON.stringify(data));
    $.ajax(obj);
}

ajax('GET', '/api/data', null, function (a) {
    a.error ? $.growl.error({message: a.error}) : console.log(a);    
});

浏览器控制台将看到{"bar": true}

最新更新