Non-root generic middlewares will not trigger if it does not explicitly contain routes #110
-
Suppose the following codes: // const express = require('express')
const HyperExpress = require('hyper-express')
console.log('Starting\u2026')
// const server = express()
const server = new HyperExpress.Server({
fast_abort: true
})
server.use((req, res, next) => {
console.log('root middleware')
next()
})
server.use('/swagger', (req, res, next) => {
console.log('/swagger middleware')
next()
})
server.set_not_found_handler((req, res) => {
console.log('not_found_handler')
res.status(404).end()
})
server.set_error_handler((req, res) => {
console.log('error_handler')
res.status(500).end()
})
;(async () => {
const port = process.env.PORT || 3001
await server.listen(port)
console.log(`Started on port ${port}`)
})() When you do This means you cannot have a generic middleware on non-root routes designed to selectively handle requests within non-root routes You could add: server.any('/swagger/*', (req, res) => {}) Which will then allow the swagger middleware to trigger properly, but that's more of a workaround than anything You will still have to programmatically call your not_found_handler directly if your middleware can't handle the request due to not found file and such (i.e. can't just do On another note, you indeed can just do the following in ExpressJS server.use('/non-root-path', express.static(path)) Because following the code example above, swagger middleware will simply trigger properly when doing |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
Great find, this makes total sense as Routes are ones that contain and execute middlewares thus If no actual routes exist for a specific range of pattern, then those middlewares will never run. I'll add a fix for this to improve this behavior in the next update. |
Beta Was this translation helpful? Give feedback.
Great find, this makes total sense as Routes are ones that contain and execute middlewares thus If no actual routes exist for a specific range of pattern, then those middlewares will never run. I'll add a fix for this to improve this behavior in the next update.