【发布时间】:2016-08-08 18:51:40
【问题描述】:
是否可以在一个请求中提供多个文件?
这是我的代码的简化版本,用于根据对我们的 node.js 服务器的请求提供我们网站的主页,该请求不包含任何参数(有缓存代码可以缓存文件数据以提高服务器效率,处理错误,等):
var http = require("http");
http.createServer(function(req, res){
res.setHeader("Access-Control-Allow-Origin", "*");
if (req.url == "/"){
res.writeHead(200, {"Content-Type": "text/html"});
fs.readFile("./pages/index/index.html", function(err, data){
res.end(data);
});
} else if (req.url == "/index.css"){
res.writeHead(200, {"Content-Type": "text/css"});
fs.readFile("./pages/index/index.css", function(err, data){
res.end(data);
});
} else if (req.url == "/index.js"){
res.writeHead(200, {"Content-Type": "application/javascript"});
fs.readFile("./pages/index/index.js", function(err, data){
res.end(data);
});
} else if (req.url == "/indexBackground.jpg"){
res.writeHead(200, {"Content-Type": "image/jpeg"});
fs.readFile("./pages/index/images/background.jpg", function(err, data){
res.end(data);
});
}
}).listen(port);
html 文件本身使用 CDN 导入外部库,对样式表、脚本和图像的引用如下所示:
<link rel="stylesheet" href="https://our-website-url/index.css">
<script type="text/javascript" src="https://our-website-url/index.js"></script>
<img src="https://our-website-url/indexBackground.jpg">
页面已正确提供,但必须发出 3 个单独的请求才能提供该页面。我想这会使网站加载速度变慢,并给服务器增加不必要的负载。
是否可以在一个请求中提供所有 3 个文件,尽管它们具有不同的内容类型?如果是这样,我们将如何引用所有在 html 文件中的一个请求中提供的这些文件,如果没有,是否有一种更有效的方法来提供我们当前使用的页面?
【问题讨论】:
标签: javascript node.js http get