+ 3

Help with nodejs module

I'm making this nodejs module that reminds a little bit of django. It's a library to make dynamic sites with express easier. And without need of ajax calls. You can choose a port and start a web server. After that you can specify routes using .get and .post methods. You can also return a view of your html file that uses html templating engine so you can pass arguments into your document. server.get("/index", function(request) { return server.view("index.html", { "title": "Home page" }); }); All of this is working great. I need help with URL rewriting. The first parameter is the path where the content is returned to. I want somehow to include url parameters on it. I was thinking something like this server.get("/index/<user>", function(request) { return server.view("index.html", { "title": "Home page" }); }).regex({ "user": "[a-zA-Z0-9]" }); The "<user>" could be replaced with any value that matches the regex. Values for those parameters should be stored in a object and passed into the callback {"user": "value"}; Currently the routes are stored in a object like this const routes = { "get": { "/index/<user>": function(request) { return "Hello World"; } }, "post": {} } If the server returns a path like "/index/toni". It should know that "/index/<user>" is the right callback for it.

12th Dec 2018, 8:41 PM
Toni Isotalo
Toni Isotalo - avatar
1 Answer
+ 2
To make it clearer, imagine the task like this. const routes = { "get": { "/index/<id>/<user>" { "callback": function(query) { return query.user; }, "params": { "id": "[0-9]", "user": "[a-zA-Z0-9]" } } }, "post": {} } function regex(path) { //Return the right function from routes object } console.log(regex("/index/1/toni")()); Edit the routes object as much as you like to store the regex expressions for each parameter.
12th Dec 2018, 9:25 PM
Toni Isotalo
Toni Isotalo - avatar