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?
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.
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
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.