我正在使用Restify服务我的静态网页。html文件调用服务器获取脚本和css文件。
我正在创建的服务器需要所有端点都以/ server /终结点为前缀
我已经能够服务器index.html文件,但是当浏览器试图包含脚本和css文件时,我得到一个404状态代码。
当我转到localhost:1337/ correctly /终结点时,我得到了正确呈现的index.html。但是,当浏览器试图下载其他文件时,它会将index.html中的路径前缀为localhost:1337/safe,而不是localhost:1337/safe/终结点。
示例:
此路径为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);
}
});
});发布于 2016-04-28 10:04:01
我能够使用restify模块中包含的serveStatic来完成这个任务。
server.get("/safe/endpoint/.*", restify.serveStatic({
directory: "./UI",
default: "index.html"
}));但是,我需要在UI文件夹中的文件夹路径前缀:
/UI/safe/endpoint/index.html但这也有一个缺点。当请求服务器时,路径必须是
example.com/safe/endpoint/而不是
example.com/safe/endpointhttps://stackoverflow.com/questions/35707376
复制相似问题