Nancy Collins
Nancy Collins

Reputation: 319

Serve static directory with dynamic URL query parameters

I am trying to serve a static directory dynamically by adding a pathname parameter to the URL.

I am able to serve the directory just fine with the following line, which renders the html and subdirectories in the browser without having to readFile etc:

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

This helped for testing but I need it to be dynamic as I am getting the directory name depending on a path variable from MongoDB, and then serving the directory based on the URL.

I've tried multiple solutions, this is my current one:

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)
      }
}

I'm not getting any error but it's not working.

Upvotes: 2

Views: 1883

Answers (1)

tom
tom

Reputation: 10529

Manipulate the req.url and return next()

First your route

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

Controller(addednext):

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)
  }
}

Last your static route (note: define it after all other routes)

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

Upvotes: 1

Related Questions