使用动态 URL 查询参数提供静态目录

Serve static directory with dynamic URL query parameters

我正在尝试通过向 URL 添加路径名参数来动态提供静态目录。

我可以通过以下行很好地为目录提供服务,它在浏览器中呈现 html 和子目录,而无需读取文件等:

app.use('/', express.static('/Users/virtuload-beta/backend/uploads/folder/subfolder/'))

这有助于测试,但我需要它是动态的,因为我根据来自 MongoDB 的路径变量获取目录名称,然后根据 URL 提供目录。

我尝试了多种解决方案,这是我目前的解决方案:

app.use('/static', express.static(path.join(__dirname, '../uploads', )), serveRouter)
router.get('/:id', FileCtrl.servepath);

-FileCtrl.js:

const servepath = async (req, res) => {
  try {
    let id = req.params.id 
    Upload.findById(id)
          .populate('Upload')
          .select('relPath') //relPath = /folder/subfolder
          .exec(function(err, upload) {
            if (err) {
              res.send(err)
            } else {
              const filepath = `${upload.relPath}`        
              console.log(filepath)    //logs folder/subfolder 
            //parse http object coming from client
              const urlObject = url.parse(req.url, true)
              console.log(urlObject)

              var myUrl = new URL(`http://localhost:8000/static/${filepath}`)
              return myUrl;
            }
          })
      } catch (e) {
        console.error(e)
      }
}

我没有收到任何错误,但它不工作。

操纵 req.url 和 return next()

首先是你的路线

router.get('/:id', FileCtrl.servepath);

控制器(已添加next):

const servepath = async (req, res, next) => {
  try {
    let id = req.params.id
    Upload.findById(id)
      .populate('Upload')
      .select('relPath') //relPath = /folder/subfolder
      .exec(function (err, upload) {
        if (err) {
          res.send(err)
        } else {
          const filepath = `${upload.relPath}`
          req.url = `/static/${pathfile}/index.html`
          return next();
        }
      })
  } catch (e) {
    console.error(e)
  }
}

最后你的静态路由(注意:在所有其他路由之后定义它)

app.use('/static', express.static(path.join(__dirname, '../uploads')), serveRouter)