How to separate files when you put variables in url in express routing

Asked 2 years ago, Updated 2 years ago, 53 views

app.use('/users',users);
router.get('/:user', function(req,res,next){

I can route using , but I would like to separate the files in case /users/:user/ or below increases.

app.use('/users/:user',users);
router.get('/', function(req,res,next){

Then I'm having trouble getting parameters in req.params.user.
How do I solve this problem?

node.js

2022-09-29 22:44

2 Answers

If you divide the Router at a location such as :id, the file side of the child Router will receive it as req.params.id.

According to the Express 4.x document, express.Router({mergeParams:true}) when generating Router takes over the parent Router variable

.

So for your example,
clenous. router.get('/', function(req,res,next){
The router of the file on the side where is written must be generated in express.Router({mergeParams:true}).


2022-09-29 22:44

This is how I do it.

Define the main file app.js as follows:

const app=require("express")()
app.use("/users", require("./routes/users"))

/users Create a users.js file that deals with the following:For users.js, define the router as follows:

const express=require("express")
const router=express.Router()

router.get('/:user', function(req,res,next){
    ...
}

module.exports=router

This way, you can access /users/12345 to get 12345 in req.params.user.

Even if the number of routers increases, the structure will be as easy to understand as follows:

app.use("/", require("."/routes/index")))
app.use("/users", require("./routes/users"))
app.use("/ranking", require("./routes/ranking"))
app.use("/bookmarks", require("./routes/bookmarks"))


2022-09-29 22:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.