I trying to express routes into a single file using app.use
app.js
import express from 'express'
import testRouter from 'testRouter'
const app = express()
app.use('/testRouter', testRouter)
app.listen(3000)
testRouter.js
import express from 'express'
const router = express.Router
router.get("/page1", function (req, res){
res.send("test")
})
export default router
using module exports is a official ways to do it and it worked
But why doesn't the router definition inside a function work like bellow?
app.js
import express from 'express'
import testRouter from 'testRouter'
const app = express()
app.use('/testRouter', function (){
const router = express.Router()
router.get("/page1", function (req, res){
res.send("test")
})
return router
}))
app.listen(3000)
I don't believe the code inside app.use('/test/Router', function() { }) executes until a user has visited your test/Router page at least once. I'm also not sure if you can use a middleware ("use") without having an eventual terminal endpoint.
Because in the official documentation testRouter is an Object
app.use('/testRouter', Object)
You put the function
app.use('/testRouter', Functon)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With