middleware to pass parameters is not working?

Issue

I am implementing the accepted solution to this post in order to pass parameters to my routes.

However, I am noticing that while the parameters seem to be set in my app.use, the parameters are not being passed to my router file.
For example,
in server.js

const app = express();

app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());

const fooRouter= require('./routes/foo');
const stringVar = 'some string';

app.use('/foo', function (req, res, next) {
  req.params = {
      connect: stringVar,
  };
  console.log(req.params); // is printing the correct value
  next();
}, fooRouter);

but in routes/foo.js

const express = require('express');
const path = require('path');
const router = express.Router();

router.get("/", (req, res) => {
  const parameters = req.params;
  console.log(req.params); // prints an empty object -> parameters.connect is undefined
  console.log("string: ", parameters.connect);
}

module.exports = router;

Am I missing something?

Solution

As pointed out in the comment, req.params is scoped to its handler function and can not be overridend from a middleware function.

Use something else instead of req.params, like req.defaults:

const express = require("express");

const app = express();
const fooRouter = express.Router();

fooRouter.use(function (req, res, next) {

    req.defaults = {
        connect: "some string"
    }

    next();

});

fooRouter.get("/", (req, res) => {
    const parameters = req.defaults;
    console.log(req.defaults);
    console.log("string: ", parameters.connect);
});

app.use('/foo', fooRouter);



app.listen(8123, (err) => {
    console.log("Listening" || err);
})
Listening
{ connect: 'some string' }
string:  some string

Tested with curl: curl -v http://127.0.0.1:8123/foo

Answered By – Marc

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published