Consolidating Routes in Express.js

bornytm

I'm a novice programmer working on a web app. As I have things right now there is a route for every single query to my database. I know there must be a way to use route parameters to direct the route to executing the right function but I am having problems in implementation.

Here is what my routes look like right now:

var database = require('./routes/database');

app.get('/query/type', database.type);
app.get('/query/test', database.test);
app.get('/query/another', database.another);
app.get('/query/onemore', database.onemore);

Each route is mapped to a function in the database.js file. I would like to try to implement something in the following format which would handle the queries with a single line:

app.get('/query/:query', database.query)

Where it executes whichever function is named in the parameter :query.

Is there an easy way of implementing this?

Third

you can create a function that will parse the parameter and use associative array to build the function you want to execute then invoke it. see code below.

function parseParam(req, res) {
  var func = database[req.param('query')];
  func(req, res);
}

app.get('/query/:query', parseParam);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Routes in express JS

From Dev

Express JS Routes

From Dev

Express.js dynamic routes

From Dev

Express js routes - overlapping params

From Dev

Express.js routes with Typescript

From Dev

Express.js - Single routes file that manages all the routes

From Dev

HTTPS express.js server and routes

From Dev

Move routes into files in Express.js

From Dev

Node.js express nested routes

From Dev

How to protect routes in express.js?

From Dev

Express js routes not working as expected with MEAN stack

From Dev

Dynamic routes with Express.js -- is this even possible?

From Dev

How to configure dynamic routes with express.js

From Dev

express js routes how to get the root

From Dev

Express JS - Use of anonymous functions for routes and middleware

From Dev

Express js routes url to correct page

From Dev

Node.js express nested routes

From Dev

Node.js + express: specify routes

From Dev

Using Express Router in routes.js

From Dev

express js routes how to get the root

From Dev

Move routes into files in Express.js

From Dev

Separating Routes and Middleware into Files (in Express.js)

From Dev

Redirecting routes in Node using Express and Passport JS

From Dev

Express.js Handle unmached routes

From Dev

node.js express routes using new RegExp

From Dev

Reload Express.js routes changes without manually restarting server

From Dev

Express.js or angular for handling routes in a MEAN application?

From Dev

How to separate routes on Node.js and Express 4?

From Dev

How to test Express.js routes with Jasmine 2.3 and SuperTest