Adding additional parameters to route handlers in Express

I'm new to using Express and I'm interested in finding a way to increase the reusability of routes. In my application, I anticipate having numerous routes that can be handled by a common function but with different templates.

For example:

app.get('/about', function(req, res) {
    res.render('about.html');
});

app.get('/', function(req, res) {
    res.render('home.html');
});

While this is a simplified example, I actually have over 30 routes like this. What I would like to achieve is something along these lines:

app.get('/about', generic.render('about.html'));

Or find a way to pass the template name to a function that then uses res.render. Is this possible in Express? My attempts at solving this issue have all led to undefined variables.

I want to avoid tightly coupling route parameters with template names like this:

app.get('/:template', function(req, res) {
    res.render(req.params.template + '.html');
});

Answer №1

If you want to simplify rendering in your application, one option is to create a middleware function to handle it for you. Here's an example:

function customRenderer(file, options) {
  options || (options = {});
  return function(request, response) {
    response.render(file, options);
  };
}

You can then easily use this middleware function like this:

app.get('/about', customRenderer('about.html'));

app.get('/', customRenderer('home.html'));

Answer №2

This is my approach:

const handleRequest = (request, response, template) => {
  response.render(template)
}

app.get('/about', (request, response) => {
  handleRequest(request, response, 'about.html')
})

Answer №3

I find this approach to be highly effective

app.use('/:page',(req, res, next) => {
    let { page } = req.params;
    res.locals.template = `${page}.html`;
    next();
  },
  renderPage
);

function renderPage(req, res){
  res.render(res.locals.template)
}


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

Issue: The plugin 0 mentioned in the file "/my dir/node_modules/babel-preset-php/src/index.js" contains an invalid property called "default"

While attempting to convert a PHP script to JavaScript using babel-preset-php, I encountered the following error: Error: Plugin 0 specified in "/media/deep/5738c180-2397-451b-b0b5-df09b7ad951e1/deepx/Documents/TestingAll/node_modules/babel-preset-php/ ...

Converting user IDs to usernames in discord.js

I'm currently developing a bot and I want to implement a feature where every time a command is used, it logs the action in the console. Here's the code snippet I've been working on: console.log(message.author ++ ,`used the comman ...

How can you move away from using the url:port scheme with socket.io?

Recently, I've been delving into node.js and socket.io, but I'm struggling to eliminate the need to type "url:port" in the browser. Instead, I want users to simply enter the URL and have everything load up, similar to my work-in-progress single p ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

having difficulty altering a string in EJS

After passing a JSON string to my EJS page, I noticed that it displays the string with inverted commas. To resolve this issue, I am looking for a way to eliminate the inverted comma's and convert the string to UPPERCASE. Does anyone know how to achiev ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Efficiency of Promise-based parallel insert queries in MySQL falls short

I have developed a code in Node.js to execute insert queries using Promise.js but unfortunately, I am encountering an exception stating "Duplicate Primary Key" entry. Here is the snippet of the code: var Promise = require("promise"); var mySql = requir ...

Exploring request parameters within an Express router

I'm currently facing an issue with accessing request parameters in my express router. In my server.js file, I have the following setup: app.use('/user/:id/profile', require('./routes/profile')); Within my ./routes/profile.js fil ...

"Mastering the art of traversing through request.body and making necessary updates on an object

As I was reviewing a MERN tutorial, specifically focusing on the "update" route, I came across some interesting code snippets. todoRoutes.route('/update/:id').post(function(req, res) { Todo.findById(req.params.id, function(err, todo) { ...

Is it possible for a JWT generated using RS256 to be decoded on the jwt.io platform?

After setting up my first Express server and implementing user authentication with jwt, I'm now searching for a method to encrypt the jwt in order to prevent users from viewing the payload on the website. I am curious if anyone is aware of an encryp ...

Express: router.route continues processing without sending the request

I've implemented the following code in my Express application: var express = require('express'); // Initializing Express var app = express(); // Creating our app using Express var bodyParser = require(' ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

Struggling with effectively executing chained and inner promises

It seems like my promises are not completing as expected due to incorrect handling. When using Promise.all(), the final result displayed with console.log(payload) is {}. Ideally, it should show something similar to this: { project1: { description: & ...

"MongoDB's .find function functions properly in the shell environment, but encounters issues when

As a newcomer to Node Express Mongo, I decided to venture into creating my own website after following tutorials. The page I'm working on is a login page. While other people's code has worked for me, my attempt didn't go as planned. Even con ...

What is the best way to retrieve the content from the MongoDB Document in my GET request?

I encountered an issue while attempting to access the Question field within the JSON document body stored in a MongoDB database. Upon executing the GET request, the result displayed as follows: { "_readableState": { "objectMode": true, "highWaterM ...

Reformat a JSON file and save as a new file

I have a lengthy list of one-level JSON data similar to the example below: json-old.json [ {"stock": "abc", "volume": "45434", "price": "31", "date": "10/12/12"}, {"stock": "abc", "volume": "45435", "price": "30", "date": "10/13/12"}, {"stock": "xyz", "vo ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

Is it possible to maintain variables across a session with numerous users when utilizing socket.io?

My code structure is designed as follows: //Route Handler that triggers when a user 'creates a session' app.post('/route', async (req, res) => { let var1 = []; let var2 = []; io.on('connection', (socket) => ...