Dlib HTTP服务器显示网站为纯HTML,没有javascript/css

dlib http server shows website as plain html with no javascript/css

本文关键字:没有 javascript css HTML 服务器 HTTP 显示 网站 Dlib      更新时间:2023-10-16

我试图在我的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();
    }
};

它确实工作,但我的浏览器只显示纯html网站没有任何javascript/css元素。这些都集成在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类型的样式表文件是文本/html,但它应该是文本/css。我相应地改变了我的响应方法,现在它工作了:

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

作为后续问题:为什么css和js文件触发请求,而不是我在html中引用的图像,这似乎可以工作,只要我能告诉混乱的布局?但无论如何,还是要谢谢你,我很想给你投票,但很遗憾我不能…

浏览器将从web服务器请求Style.css和script .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");