使用默认前缀的 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