1

我尝试在我的 c++ 程序中实现一个小型 http 服务器,以使用 dlib 库 ( http://dlib.net/network.html#server_http ) 将网站用作接口。这段代码应该做的是根据请求读取输入的 html 文件并返回它。

class web_server : public server_http
{
    const std::string on_request ( 
        const incoming_things& incoming,
        outgoing_things& outgoing
    )
    {
        ostringstream sout;
        sout<<get_file_contents("Seite.html");
        return sout.str();
    }

};

它确实有效,但我的浏览器只显示没有任何 javascript/css 元素的纯 html 网站。这些通过以下方式集成到 html 文件中:

   <script type="text/javascript" src="scripte.js")>
   </script>
   <link rel="stylesheet" type="text/css" href="Style.css"> 

如果我直接用浏览器打开它,html 看起来很好。提前致谢

编辑:谢谢戴维斯金我至少让javascript工作了,而css仍然拒绝工作。我设法放入一个通用响应,现在将任何请求的文件作为字符串发送:on_request 的正文:

ostringstream sout;
sout<<get_file_contents("Seite.html");
cout << "request path: " << incoming.path << endl;
string filename=incoming.path.substr(1,incoming.path.length()); 
if (incoming.path.substr(0,1) == "/" && incoming.path.length()>1) return get_file_contents(filename.c_str());
return sout.str();

再次编辑:它现在可以工作了。Chrome给了我提示,它说样式表文件的MIME类型是text/html,但它应该是text/css。我相应地更改了我的响应方法,它现在可以工作了:

if (incoming.path=="/Style.css") outgoing.headers["Content-Type"] == "text/css";

作为一个后续问题:为什么 css 和 js 文件会触发请求,而不是我在 html 中引用的图像,据我所知,这些图像似乎对混乱的布局有效?但是无论如何还是非常感谢,我会支持你,但遗憾的是我不能......

4

1 回答 1

0

浏览器将从 Web 服务器请求 Style.css 和 scripte.js 文件,但按照您编写的方式,它只会响应 Seite.html 文件。所以你必须在你的 on_request 方法中添加这样的东西:

cout << "request path: " << incoming.path << endl;
if (incoming.path == "/scripte.js")
    return get_file_contents("scripte.js");
else if (incoming.path == "/Style.css")
    return get_file_contents("Style.css");
于 2013-03-14T21:28:04.940 回答