【问题标题】:Serve static directory with dynamic URL query parameters使用动态 URL 查询参数提供静态目录
【发布时间】:2020-01-20 20:37:08
【问题描述】:

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

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

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

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

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

  • app.js:
app.use('/static', express.static(path.join(__dirname, '../uploads', )), serveRouter)
  • routes.js:
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)
      }
}

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

【问题讨论】:

    标签: javascript node.js express url routing


    【解决方案1】:

    操作req.url并返回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)
    

    【讨论】:

    • 它仍然无法正常工作,它说无法获得状态 404
    • 将此用于静态路由以记录修改后的 url app.use(function (req, res, next) {console.log(req.url); next();}); url 正确吗?
    • 我知道这应该像我 console.log(req.url) 一样工作(而 req.url = /${pathfile} 被注释掉)我得到了原始 url 中指定的用户 ID 参数,当我使用 req.url = /${pathfile} console.log(req.url) 时,我得到了目录路径。但是还是不行
    • /${pathfile} 不是静态文件吗?
    • 您的路线我们收听/static/,并且需要指定一个文件。所以应该是/static/${pathfile}/index.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多