Web 服务器 - 如何指定正在使用的服务器

web servers - How to specify server being used

我正在编写一个简单的网络服务器。这是我的 Python 代码:

import http.server

from os import curdir, sep

class RequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path.endswith(".php"):
            f = open(curdir + sep + self.path)

            self.send_response(200);
            self.send_header("Content-type", "text/php")
            self.end_headers()

            self.wfile.write(f.read())
            f.close()

        else:
            self.send_error(404, "Cannot open non-html file")

httpd = http.server.HTTPServer(("", 8000), RequestHandler)
httpd.serve_forever()

这是 HTML 代码:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Hello</title>    

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    </head>

    <body>
        <input type="button" value="Click me" id="button">

        <script>

            var buttonOnClick = 
                function() {

                    var updateButton =
                        function(result) {  
                            $("#button").replaceWith("<p>" + result + "<p>");
                          };


                    $.get("text.php", updateButton);
                };

            $("#button").click(buttonOnClick);  

        </script>
    </body>
</html>

text.php

<?php  
        echo "Hello!";  
?>

当我在 Apache 上 运行 时,我得到了预期的结果。当您单击该按钮时,它会变为 "Hello!"。但是,当我 运行 它关闭 Apache 时,页面显示 ERR_CONNECTION_REFUSED 错误。这告诉我我的网页使用 Apache 作为其服务器,而不是我的 Python 代码。我不知道如何让我的 HTML 和 jQuery 代码使用我的自定义 Web 服务器而不是 Apache。这可能是一个非常简单的问题,但我很困惑。

如果我的代码有任何可以改进的地方,请告诉我。

端口号在 URL 中的主机名之后,而不是在末尾。

并且由于您的 HTTP 服务器没有启用 SSL,您必须使用 http: 作为协议,而不是 https:

所以 URL 应该是 http://localhost:8000/webprograms/testwebserver/index.html