如何使用路由器路径作为根目录来拥有Express.js服务器文件?

我有这样的目录结构

root
  private
    js
    css
    index.html
  app.js
  privateRouter.js
  ...

在我的index.html中,我使用如下相对路径引用js和css文件:

<link rel="stylesheet" href="css/index.css"/>
<script src="js/index.js"></script>

在服务器端,我有一个专用路由器在提供以下文件之前检查身份验证:

在app.js中:

app.use("/private", privateRouter);

在privateRouter.js中:

router.use((req, res, next) => {
    isAuthenticated(req) ? next() : res.redirect("/");
});

router.get('/', function(req, res, next) {
    res.sendFile(require('path').join(__dirname + "/private/index.html"));
});

So now if I visit http://mywebsite.com/private I will get the the index.html, but the request of js/css files from the browser comes back to the server as http://mywebsite.com/js instead of http://mywebsite.com/private/js, thus returns file not found.

Alternatively if I serve files statically, the browser knows to request from /private/js:

app.use("/private", express.static(path.join(__dirname, 'private')));

But I can't server statically because I need to authenticate specific files and not serve all files publicly. And I don't want to have to append private/ before all file references on client side. I don't understand why when serving statically the server knows to use /private as root but when using a router it uses / as root.

How can I keep the url as http://mywebsite.com/private while not having to append private/ in all file references on the client side?

我是express.js的新手,这对我来说也很困难。我认为我从根本上误解了express.js的工作原理。谢谢你的帮助!

评论
  • 老鸡抓小鹰
    老鸡抓小鹰 回复

    您可以使用中间件为内部路由修改请求的URL:

    app.use((req,res,next)=>{
      req.url = "/private" + req.url; // prepend "/private" to the url
      next();
    });
    

    You can also set the base URL using the base tag, which means you only need to specify the base URL once per page.

    <html>
      <head>
        <base href="private">
        <link rel="stylesheet" href="css/index.css"/>
        <script src="js/index.js"></script>
      </head>
    </html>
    

    然后,应将请求发送到:

    • /private/css/index.css
    • /private/js/index.js

    但是,您仍然需要代码来处理这些路径,否则,您仍然会收到404 not found错误。