Leon Gaban
Leon Gaban

Reputation: 39018

Cannot read property 'name' of undefined in route param

Following along in a ExpressJS course on TUTS+

I have the following (exact from video):

var express = require('express'),
app     = express();

app.get('/name/:name', function (req, res) {
    res.send('Your name is ' + res.params.name);
});

app.listen(3000);

However if I go to http://localhost:3000/name/ error: Cannot GET /name/

If I goto http://localhost:3000/name/Leon

error:

TypeError: Cannot read property 'name' of undefined
   at /Users/leongaban/Projects/Node/expressApp/server3.js:5:39
   at Layer.handle [as handle_request] (/Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/layer.js:82:5)
   at next (/Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/route.js:100:13)
   at Route.dispatch (/Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/route.js:81:3)
   at Layer.handle [as handle_request] (/Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/layer.js:82:5)
   at /Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/index.js:235:24
   at param (/Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/index.js:332:14)
   at param (/Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/index.js:348:14)
   at Function.proto.process_params (/Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/index.js:392:3)
   at /Users/leongaban/Projects/Node/expressApp/node_modules/express/lib/router/index.js:229:12

Not sure what I'm missing?

Upvotes: 0

Views: 1844

Answers (2)

A.B
A.B

Reputation: 20445

Request object contains parameters not response. Thought of the request you make to ther server with request paarameters in it? so Request object holds them

you need req.params.name

Upvotes: 1

lukewestby
lukewestby

Reputation: 1207

The params are on the req. Use req.params.name.

Regarding the Cannot GET /name/, if you specify a parameter in the route leaving that portion of the url empty will not match your route. You have to populate the :name portion of the url to hit the route.

Upvotes: 1

Related Questions