【发布时间】:2016-06-12 22:53:45
【问题描述】:
我正在使用 Restify 来提供我的静态网页。 html 文件调用服务器获取脚本和 css 文件。
我正在创建的服务器需要所有端点都以 /safe/endpoint 为前缀
我已经能够提供 index.html 文件,但是当浏览器尝试包含脚本和 css 文件时,我得到了 404 状态代码。
当我转到 localhost:1337/safe/endpoint 时,我得到了正确呈现的 index.html。但是当浏览器尝试下载其他文件时,它会在 index.html 中的路径前加上 localhost:1337/safe 而不是 localhost:1337/safe/endpoint。
示例:
index.html 使用此路径提供服务
localhost:1337/safe/endpoint
在 index.html 文件中我有这个包含
<script src="app/js/thing.js"></script>
当浏览器尝试获取 thing.js 时使用此路径
localhost:1337/safe/app/js/thing.js
而不是
localhost:1337/safe/endpoint/app/js/thing.js
服务器代码如下所示
server.get("/safe/endpoint", function(req, res){
fs.readFile("./frontend/index.html", "utf8", function(err, data){
if(err){
res.setHeader('content-type', 'text/plain');
res.send(404, "No index.html found");
} else {
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end(data);
}
});
});
server.get("/safe/endpoint/app/.*", function(req, res){
var filePath = "./frontend" + req.url.split("/safe/endpoint")[1];
fs.readFile(filePath, "utf8", function(err, data){
if(err){
res.setHeader('content-type', 'text/plain');
res.send(404, req.url + " not found");
} else {
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end(data);
}
});
});
【问题讨论】:
-
仅供参考:您可以做其他人所做的事情,使用可从客户端访问的
/public文件夹,以及所有静态文件的静态路由,无论如何都无法访问其他文件,不需要“安全/端点”。 -
@adeneo 是一种仪式。文件夹上的 express.static 并通过
/public提供服务是最好的方法。 -
我正在使用restify。由于 restify.serveStatic 中的一项功能,您可以为静态服务器定义一个基本目录。然后端点的路径成为基目录上的后修复。要使用它,我需要创建一个文件夹结构(即 frontent/safe/endpoint/app/js/thing.js 而不是 frontend/app/js/thing.js)。我试图避免这种文件夹结构。 stackoverflow.com/questions/19281654/…
标签: javascript node.js browser static-files