【问题标题】:express static: serve pages with dynamic contentexpress static:为页面提供动态内容
【发布时间】:2018-04-11 15:50:36
【问题描述】:

我正在使用 express.static 提供一些页面,假设您浏览到:

https://amazing.com/static

它提供目录的内容,在我的例子中是一个 index.html 和一个 JS 脚本,太棒了!

现在,我想实现以下目标:

如果你浏览到

https://amazing.com/static/whatever

我想提供与上述相同的页面,但保持“whatever”网址不变,其中“whatever”是一些动态内容的标识符。

客户端应该在该 URL 上,以便客户端 JS 脚本在加载和显示静态页面后可以根据路径获取内容。

不确定是否可以使用 express.static 来实现 - 我是 node / express 生态系统的新手...

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    您可以做到这一点,但不能使用express.static()。您需要定义一个动态路由,忽略路径中的标识符并使​​用所需的静态文件进行响应:

    // ...
    const { resolve } = require('path');
    // wherever your static files are, relative to this file
    const myStaticDirectory = './www';
    
    app.use('/static', express.static(resolve(__dirname, myStaticDirectory)));
    
    app.get('/static/:id', (req, res) => {
      res.sendFile(resolve(__dirname, myStaticDirectory, 'index.html'));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多