如何用Crow C++返回CSS/JS文件?遇404及请求卡顿问题求助
问题分析与解决方案
问题1:静态文件返回404错误
你代码里的crow::mustache::set_global_base只负责模板文件的加载路径,而res.set_static_file_info查找文件时是基于程序运行的工作目录,和mustache的全局基础路径无关。你传入的"style/load.css"是相对路径,程序找不到对应文件,所以返回404。
解决方法
方法一:使用绝对路径
直接给set_static_file_info传入文件的完整绝对路径:CROW_ROUTE(app, "/style/load.css") ([] () { crow::response res; // 传入完整的文件路径 res.set_static_file_info("/home/cereza/testing/src/frontend/src/style/load.css"); return res; });方法二:配置静态文件路由(更推荐)
用Crow内置的静态文件路由功能,一次性映射整个静态文件目录,无需逐个编写路由:void foo() { crow::SimpleApp app; crow::mustache::set_global_base("/home/cereza/testing/src/frontend/src/"); // 将/style/路径映射到对应的静态文件目录 app.route_static("/style/", "/home/cereza/testing/src/frontend/src/style/"); CROW_ROUTE(app, "/") ([] () { auto page = crow::mustache::load("html/index.html"); return page.render(); }); app.port(8080).run(); }
问题2:手动读取文件请求卡住
手动读取文件后请求卡住,是因为你没有设置正确的响应头(Content-Type)和状态码,浏览器无法识别响应是否完成。
解决方法
手动读取文件时,必须明确设置CSS对应的Content-Type,同时处理文件不存在的场景:
CROW_ROUTE(app, "/style/load.css") ([] () { crow::response res; std::string file_path = "/home/cereza/testing/src/frontend/src/style/load.css"; std::ifstream css_file(file_path); if (css_file.is_open()) { // 读取文件内容到响应体 res.body.assign(std::istreambuf_iterator<char>(css_file), std::istreambuf_iterator<char>()); // 设置CSS对应的Content-Type res.set_header("Content-Type", "text/css"); res.code = 200; // 标记请求成功 } else { res.code = 404; // 文件不存在返回404 res.body = "File not found"; } return res; });
内容的提问来源于stack exchange,提问作者chief_rocka69
相关产品推荐
相关产品推荐

