使用AJAX调用Flask Server在显着延迟后返回响应

时间:2017-12-03 12:24:55

标签: javascript ajax rest flask server

我有2台服务器在localhost上运行,具有不同的端口。 一个是python中的简单烧瓶服务器,代码添加在下面:

from flask import Flask,jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/',methods=['GET'])
def index():
    return jsonify("Hello, World!")

if __name__ == '__main__':
    app.run(debug=True,threaded=True)

当我从邮递员或任何现有客户发送GET请求时,它就像一个魅力。但是当我使用Apache来托管一些现有的JavaScript AJAX代码来做同样的事情时,响应会有很大的延迟。这是代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Title</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet'  type='text/css'>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

    <script>
    function loadDoc() {

      var xhttp = new XMLHttpRequest();

      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          alert(this.responseText)
          document.getElementById("demo").innerHTML =
          this.responseText;
        }
      };
      xhttp.open("GET", "http://localhost:5000/", true);
      xhttp.send();
    }
    </script>


</head>

<body>
  <div id="demo">
  <h1>Welcome to our application</h1>
  <br>
<button type="button" onclick="loadDoc()">Print Hello World!</button>
</div>
</body>
</html>

有时我甚至不会收到回复。任何快速建议都会有所帮助。

1 个答案:

答案 0 :(得分:0)

在WSGI应用程序的文档中找到答案:

在支持ipv6并配置了现代Linux系统,OS X 10.4或更高版本以及Windows Vista的操作系统上,如果访问本地服务器,某些浏览器可能会非常慢。原因是有时“localhost”被配置为在ipv4和ipv6套接字上都可用,并且一些浏览器将首先尝试访问ipv6然后再访问ipv4。尝试删除

ssh ${node.username}@${node.hostname} "reboot & exit"

来自系统上的hosts文件。