Javascript newbie here..
I've trying to run the example code given in the routes documentation.
Code:
var Router = require('routes');
var router = new Router();
router.addRoute('/admin/*?', auth);
router.addRoute('/admin/users', adminUsers);
http.createServer(function (req, res) {
var path = url.parse(req.url).pathname;
var match = router.match(path);
match.fn(req, res, match);
}).listen(1337)
// authenticate the user and pass them on to
// the next route, or respond with 403.
function auth(req, res, match) {
if (checkUser(req)) {
match = match.next();
if (match) match.fn(req, res, match);
return;
}
res.statusCode = 403;
res.end()
}
// render the admin.users page
function adminUsers(req, res, match) {
// send user list
res.statusCode = 200;
res.end();
}
I can run this via node app.js and it starts up fine. However, when I hit http://localhost:1337/admin I get the following error:
TypeError: Cannot call method 'fn' of undefined
To make sure I wasn't doing something wrong in the server, I reset it back to the example Node app:
http.createServer(function (req, res) {
.write("Hello world!");
res.end();
}).listen(1337)
And this runs fine. I can hit localhost and see it print out hello world. So why am I getting a type error when I run the routes example code?
Look at the path formats here: https://www.npmjs.com/package/routes#path-formats
Clearly, having used router.addRoute('/admin/*?', auth);, we cannot expect to get served at localhost:1337/admin or localhost:1337/admin/
To achieve this, just remove the ?.
Use simply router.addRoute('/admin/*', auth); and you are good to go with localhost:1337/admin/. Though I still doubt that localhost:1337/admin will work. For that as the documentation says, we need to use router.addRoute('/admin', auth);