req.params is throwing "undefined" in Router file

I am doing a practise project in Node/Express.

My server.js looks like this:

const express = require("express")
const app = express()
const bodyParser = require("body-parser")
const morgan = require("morgan")
const { get } = require("http")

const PORT = 3000

const budgetRoute = require("./routes/Budget")
const envelopeRoute = require("./routes/Envelopes")
const envelopeNameRoute =require("./routes/Envelopes_name")
const envelopeTransferRoute =require("./routes/Envelopes_transfer")

global.envelopes = []
global.totalBudget = 0


app.use("/envelopes", envelopeRoute)
app.use("/envelopes/:name", envelopeNameRoute)
app.use("/envelopes/transfer/:name", envelopeTransferRoute)
app.use("/budget", budgetRoute)

app.listen(PORT, () =>{
    console.log(`Listening on port ${PORT}`)

now in my Route file routes/Envelopes_name I have this:

router.put("/", (req,res,next)=>{
    const envelopeToChangeName =
    const envelopeName =
    const envelopeBudget = req.query.budget
    const reqEnvelope = envelopes.find(envelope => envelopeToChangeName)
        reqEnvelope.budget = envelopeBudget 
    if(envelopeName){ = envelopeName

after sending request localhost:3000/envelopes/groceries?name=taxes it should change the name of the envelope from "groceries" to "taxes". For some reason is "undefined" and I have error "TypeError: Cannot set properties of undefined (setting ‘name’)". When I had it all in one file, without routers, it worked perfectly. Any ideas?

>Solution :

I think you need to add { mergeParams: true } to make the params available, because you use another router file then where you define the route.

See Express docs

Leave a Reply