Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grouping express routes into a single file

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)
like image 717
tsumuri Avatar asked Jan 21 '26 11:01

tsumuri


2 Answers

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.

like image 138
djechlin Avatar answered Jan 24 '26 00:01

djechlin


Because in the official documentation testRouter is an Object

app.use('/testRouter', Object)

You put the function

app.use('/testRouter', Functon)
like image 31
italant Avatar answered Jan 24 '26 02:01

italant