【问题标题】:web servers - How to specify server being usedWeb 服务器 - 如何指定正在使用的服务器
【发布时间】:2015-10-01 23:20:25
【问题描述】:

我正在编写一个简单的 Web 服务器。这是我的 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>

文本.php

<?php  
        echo "Hello!";  
?>

当我在 Apache 上运行它时,我得到了预期的结果。按钮变为“您好!”当你点击它。但是,当我在关闭 Apache 的情况下运行它时,页面显示 ERR_CONNECTION_REFUSED 错误。这告诉我我的网页使用 Apache 作为其服务器,而不是我的 Python 代码。我无法弄清楚如何让我的 HTML 和 jQuery 代码使用我的自定义 Web 服务器而不是 Apache。这可能是一个非常简单的问题,但我很难过。

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

【问题讨论】:

  • 自定义服务器在 8000 端口上运行。您是否在 URL 中的服务器名称后添加了:8000
  • 我尝试使用https://localhost:8000/webprograms/testwebserver/index.html。它给了我一个 SSL 连接错误。

标签: php jquery python apache webserver


【解决方案1】:

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

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

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

【讨论】:

  • 它说“没有收到数据”,我假设这是一个程序员错误。如何在 Python 代码中解决这个问题?
  • webprograms是你运行网络服务器时当前目录的子目录吗?
  • 所有这些文件所在的目录是C:\xampp\htdocs\WebPrograms\TestWebServer
  • 运行 Python 脚本时您的当前目录是什么?由于您将 URL 路径连接到当前目录,因此您需要从 \xampp\htdocs 运行程序以访问具有该 URL 的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
相关资源
最近更新 更多