繁体   English   中英

使用带有默认前缀的nodejs提供静态html文件

[英]Serving static html files with nodejs with default prefix

我正在使用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);
    }
  });
});

我能够使用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/endpoint

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM