简体   繁体   中英

How to bind url parameters to callback function in express/node.js?

I have callback function which takes 4 parameters like

function findFriend(req, res, name, year) {
// here I have tried to read

}

and I want to bind to url like

app.get('/api/name/:name/year/:year/student', students.findFriend);

and I expect to bind name to name and year to year but it is undefined. I also have tried to read paramters as req.params.name and req.params.year (also req.query.name and req.query.year) but it is always undefined. How to bind url parameters to callback function ?

The values for name and year will come inside the req.params.name and req.params.year respectively.

Express does not know how to pass them as individual parameters to your function, but you can either (1) handle them inside your students.findFriend function or (2) define a wrapper function that will extract them from the req.params object and pass them down.

app.get('/api/name/:name/year/:year/student', function(req, res) {
  students.findFriend(req, res, req.params.name, req.params.year)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM