【问题标题】:Redundant server information in my Flask API response我的 Flask API 响应中的冗余服务器信息
【发布时间】:2018-01-03 03:03:11
【问题描述】:

我正在 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"}}

为什么会发生这种情况,谁能提供一些可能的想法?

【问题讨论】:

  • http 响应有标头 - 响应的内容是有效的 JSON。你用什么来发送请求?
  • @PaulBecotte 我在我的 js 前端使用 ajax
  • 这些信息是 HTTP 响应标头,您的 JSON 位于 HTTP 响应正文中。您能否展示一下您如何在前端解析响应的 sn-p?
  • @erikng 更新了问题

标签: python-2.7 rest flask


【解决方案1】:

只需要返回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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 2010-10-27
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多