You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python HTTP服务器未响应JavaScript请求,求排查解决建议

Python HTTP服务器未响应JavaScript XMLHttpRequest请求的排查与解决

一、先修复JavaScript代码的语法错误

你的XHR代码存在语法错误:onreadystatechange的回调函数未正确闭合,导致xhr.open()和xhr.send()被嵌套在回调函数内部,请求根本没有被执行。

修正后的JS代码:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       x = this.responseText;
       console.log(x); // 建议添加日志,便于调试响应内容
    }
}; // 补充缺失的函数闭合花括号
xhr.open('GET', 'http://127.0.0.1:8080/example', true);
xhr.send();

二、修复Python服务器的响应发送问题

你的Python服务器do_GET方法中手动调用了self.wfile.close(),这会导致响应流被提前关闭,客户端可能无法接收到完整响应。BaseHTTPRequestHandler框架会自动处理响应流的关闭,无需手动操作。

修正后的Python服务器do_GET方法:

def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
    self.wfile.write(bytes("<p>GET: %s</p>" % self.path, "utf-8"))
    self.wfile.write(bytes("<body>", "utf-8"))
    self.wfile.write(bytes("<p>This is do_GET of HTTP server.</p>", "utf-8"))
    self.wfile.write(bytes("</body></html>", "utf-8"))
    # 移除 self.wfile.close() 这一行

三、处理跨域资源共享(CORS)问题

如果你的JavaScript代码在file://协议(直接打开本地HTML文件)或其他端口/域名下运行,浏览器会因跨域政策拦截响应。需要在Python服务器中添加CORS响应头。

给Python服务器添加CORS支持:

from http.server import BaseHTTPRequestHandler, HTTPServer

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    # 重写end_headers方法,注入CORS头
    def end_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        super().end_headers()
    
    # 处理浏览器预请求OPTIONS
    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()
    
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
        self.wfile.write(bytes("<p>GET: %s</p>" % self.path, "utf-8"))
        self.wfile.write(bytes("<body>", "utf-8"))
        self.wfile.write(bytes("<p>This is do_GET of HTTP server.</p>", "utf-8"))
        self.wfile.write(bytes("</body></html>", "utf-8"))

    def do_POST(self):
        content_length = int(self.headers.get("Content-Length"))
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(body)
    
if __name__ == "__main__":        
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))
    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass
    webServer.server_close()
    print("Server stopped.")

四、调试建议

  • 打开浏览器控制台(F12)查看网络请求:确认请求是否发送成功,检查请求状态码、响应头和响应体。
  • 查看控制台日志:排查是否有语法错误、跨域错误等提示。
  • 在Python服务器的do_GET/do_POST方法开头添加日志,比如print(f"Received {self.command} request for {self.path}"),确认服务器是否收到请求。

内容的提问来源于stack exchange,提问作者edjco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:35:57