Routing is the starting point in web development, all requests are made through a route whether they are get request or post request. Moreover, all routes in the application need to be defined at the point when the application start to run so that different request should be made through those routes later. If a user tries to make a request through a route that is not defined ahead of time, an error will occur.
To facilitate the making of routes, we could put all routes in a folder called “route” in the root folder in which there will be many sub-folders for specific routes.
In Express.js web framework, to define route, we need to use a route instance by calling express.Router( ) class.
//routes/index.js
import express from 'express'
const indexRoute = express.Router()
indexRoute.get('/',(req,res,next)=>{
res.send('ស្វាគមន៍មកកាន់ទំព័រដើម!')
})
export default indexRoute
The code above is the defining of a route for visitor to make a get request to see the home page. However, to make the code in the module above run when the application starts, we need to import it into the application entry point which is the index.js file in the root folder. In short, all routes must be imported into the entry point directly or via other modules for them to be defined when the application starts to run.
We should also notice that the function in the route above is not called yet when the route is defined, it will be called only when a visitor make a get request through this route.
// index.js
// npm install express
import express from 'express'
const app = express()
const port = process.env.PORT || 8000
import mydb from './model/conMongoDB.js'
import indexRoute from './route/index.js'
app.use('/',async function(req,res,next){
req.mydb = await mydb
next()
})
app.use('/',indexRoute)
app.listen(port, () => {
console.log(`This app is listening to the port ${port}`)
})