Home > Net >  req.params is throwing "undefined" in Router file
req.params is throwing "undefined" in Router file

Time:06-16

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(bodyParser.json())
app.use(morgan("dev"))

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 = req.params.name
    const envelopeName = req.query.name
    const envelopeBudget = req.query.budget
    const reqEnvelope = envelopes.find(envelope => envelopeToChangeName)
    if(envelopeBudget){
        reqEnvelope.budget = envelopeBudget 
    }
    if(envelopeName){
        reqEnvelope.name = envelopeName
    }
    res.status(201).send(reqEnvelope)
})

after sending request localhost:3000/envelopes/groceries?name=taxes it should change the name of the envelope from "groceries" to "taxes". For some reason req.params.name 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?

CodePudding user response:

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

  • Related