jfhbrook / node-ecstatic

A static file server middleware that works with core http, express or on the CLI!
https://github.com/jfhbrook/node-ecstatic
MIT License
975 stars 194 forks source link

baseDir does not work correctly when mounted non-root, and is not necessary #235

Closed panlina closed 5 years ago

panlina commented 5 years ago

Previously I posted issue #233 , but now I think that is not about absolute path/relative path, but the way this middleware works. The goal may be achieved by using the middleware like this: app.use('/', ecstatic({.., baseDir: "a"}));, However, if I use it like this: app.use('/a', ecstatic({.., baseDir: "a"})); //no matter whether baseDir is set, it does not work correctly as I addressed in #233 , but using a middleware like that is quite common in express apps. Think a little further, due to express's mounting feature, as stated in req.originalUrl, baseDir might be unnecessary at the 1st place. The user can just mount the ecstatic at the path they want, and let express strip the base for you: app.use('/a', ecstatic({..})); This works better, because this makes the middleware more portable, in the sense that the middleware does not need to know which path is it working on. The middleware can just assume the req.url contains barely the file path, which simplifies things a lot. How do you think? @jfhbrook

imcuttle commented 5 years ago

@jfhbrook @panlina I have same issue here. I wrapped ecstatic to solve it temporarily

function wrapStatic(opts = {}) {
  return function(req, res, next) {
    const baseDir = typeof opts.baseDir === 'string' ? opts.baseDir : req.baseUrl
    req.url = req.originalUrl || req.url

    let fn = ecstatic(
      Object.assign({}, opts, {
        baseDir
      })
    )

    if (!Array.isArray(fn)) {
      fn = [fn]
    }
    fn.forEach(handle => {
      typeof handle === 'function' && handle.apply(this, arguments)
    })
  }
}
panlina commented 5 years ago

Really want ecstatic to be able to work in the way requested. But seems @jfhbrook is busy with other projects.

jfhbrook commented 5 years ago

I don't have a strong opinion. I tend to use ecstatic from the cli these days, and I think most people working w/ express use express's static fileserving middleware.

I can take pull requests though! It sounds like you know what the behavior is you want and how to get it.

panlina commented 5 years ago

Thank you for taking time to have a look. I'm working on a pull request now.

jfhbrook commented 5 years ago

closing this and tracking with your PR