从 Flask 响应 XMLHttpRequest() 时出现空响应

Eli*_*aum 2 javascript python xmlhttprequest flask

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

这是服务器端的 Flask 路线。

@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

Run Code Online (Sandbox Code Playgroud)

这是 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);
}
Run Code Online (Sandbox Code Playgroud)

但状态为 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
Run Code Online (Sandbox Code Playgroud)

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

sli*_*wp2 5

您需要监听对象load的事件xhttp并为其添加事件处理程序。请参阅使用 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')
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

的输出console.log

xhttp.responseText:
xhttp.status: 0
this.responseText: success
this.status: 200
Run Code Online (Sandbox Code Playgroud)