Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
How to pass req.params as an an argument to a middleware function?

I'm trying to figure out a way to use req.params as an argument in my middleware. Take this (obviously broken) code for example:

router.post('/:myParam', checkSchema(schemas[req.params.myParam]), async (req, res, next) => {
  // do stuff
})

The goal here is that I am using express-validator and I load a dynamic schema based on what param is passed. The above code is obviously broken because I don't yet have the scope to access the req variable, I'm just trying to illustrate what I'm trying to accomplish.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

if you know the possible params ahead, you could do something like the following:

router.post("/:myParam", checkSchema("soccer"), async (req, res, next) => {});

//checkSchema.JS
    const soccerSchema = require("../schemas/soccerSchema");
    const swimmingSchema = require("../schemas/swimmingSchema");

    module.exports = function (schemaName) {
      return (req, res, next) => {
        const schemas = { soccer: soccerSchema, swimming: swimmingSchema };
        //You can access it here schemas[schemaName]
        console.log(schemas[schemaName]);
        next();
      };
    };

about 4 years ago · Juan Pablo Isaza Report

0

You can directly call schemas(req.params.myParam) inside the checkSchema middleware since the middleware will have access to the request object.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!