【问题标题】:Empty response when responding to XMLHttpRequest() from Flask从 Flask 响应 XMLHttpRequest() 时的空响应
【发布时间】:2020-08-29 04:06:01
【问题描述】:

我有一个烧瓶应用程序,它使用客户端上的 XMLHttpRequest() 对象处理来自 javascript 文件的发布请求。请注意,此应用程序在 localhost 上运行。 我试图根据服务器是否引发异常来返回响应。服务器处理请求很好,但我无法访问响应。

这是服务器端的烧瓶路由。

@app.route("/updatecontact", methods=['POST', 'GET'])
def update_contact():
    if request.method == 'POST':
        try:
            sqltools.update(request.json['msg'])
            return "success"
        except Exception as e:
            return str(e), 400

这里是 javascript 中的函数,它发送 POST 请求并(旨在)处理返回的响应

function pushtodatabase(key, newvals) {
    var xhttp = new XMLHttpRequest()
    xhttp.open('POST', 'updatecontact', true);
    var msg = {"msg": newvals.join("|")};
    var msgjson = JSON.stringify(msg)
    xhttp.setRequestHeader("Content-type", 'application/json;charset=UTF-8');
    xhttp.send(msgjson);
    console.log(xhttp.responseText);
    console.log(xhttp.status);
}

但状态为 0,responseText 为空

我尝试过在烧瓶中使用不同的响应类型。我试过添加这些标题

            resp = Response("Foo bar baz")
            resp.headers['Access-Control-Allow-Origin'] = '*'
            resp.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, PUT"
            resp.status_code = 200
            return resp

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: javascript python flask xmlhttprequest


    【解决方案1】:

    您需要监听xhttp 对象的load 事件并为其添加事件处理程序。见Using XMLHttpRequest

    例如

    main.py:

    from flask import Flask, request, render_template
    
    app = Flask(__name__)
    
    
    @app.route('/updatecontact', methods=['POST', 'GET'])
    def update_contact():
        if request.method == 'POST':
            try:
                return 'success'
            except Exception as e:
                return str(e), 400
        else:
            return render_template('updatecontact.html')
    

    updatecontact.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>update contact</title>
      </head>
      <body></body>
      <script>
        function pushtodatabase(key, newvals) {
          var xhttp = new XMLHttpRequest();
          xhttp.open('POST', 'updatecontact', true);
          var msg = { msg: newvals.join('|') };
          var msgjson = JSON.stringify(msg);
          xhttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
          xhttp.send(msgjson);
    
          xhttp.addEventListener('load', reqListener);
    
          console.log('xhttp.responseText:', xhttp.responseText);
          console.log('xhttp.status:', xhttp.status);
        }
    
        function reqListener() {
          console.log('this.responseText:', this.responseText);
          console.log('this.status:', this.status);
        }
    
        window.onload = function () {
          pushtodatabase('key,', ['a', 'b']);
        };
      </script>
    </html>
    

    console.log 的输出:

    xhttp.responseText:
    xhttp.status: 0
    this.responseText: success
    this.status: 200
    

    【讨论】:

    • 这行得通。如果我想将它捕获为变量来使用,我会从 reqlistner 函数中返回它吗?
    猜你喜欢
    • 2018-11-19
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    相关资源
    最近更新 更多