Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Created Jan 31, 2016
Embed
What would you like to do?
path-to-regexp example
var express = require('express');
var pathToRegexp = require('path-to-regexp');
var entriesIndex = function() {
return 'entry list html';
};
var entriesShow = function(params) {
return 'entry item html : ' + params[0];
};
var notFound = function() {
return 'not found';
};
var getRoutes = function() {
return [
['/entries', entriesIndex],
['/entries/:id', entriesShow],
['*', notFound]
].map(function(route) {
return {
re: pathToRegexp(route[0]),
handler: route[1]
};
});
}
var render = function(routes, path) {
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var match = route.re.exec(path);
if (match) return route.handler(match.slice(1));
}
return null;
};
var main = function() {
var routes = getRoutes();
var app = express();
app.get('*', function(req, res) {
res.send(render(routes, req.path));
});
app.listen(3000);
};
main();
@bouzuya
Copy link
Author

bouzuya commented Jan 31, 2016

$ npm i express path-to-regexp
$ node server.js
$ curl http://localhost:3000/entries
entry list html

$ curl http://localhost:3000/entries/123
entry item html : 123

$ curl http://localhost:3000/foo        
not found

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment