1

I have this alias middleware which supposed to manually initialized the queries.

exports.aliasTopTours = (req, res, next) => {
  req.query.limit = '5';
  req.query.sort = '-ratingsAverage,price';
  req.query.fields = 'name,price,ratingsAverage,summary,difficulty';

  next();
};

The problem is the req.query. I get an empty object instead of an object with the set fields in it. I'm not sure why is it doing it it's really puzzling.

4
  • Demonstrate where req.query is empty and how that code block relates to the middleware code you wrote here. Commented Apr 12 at 22:55
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Apr 13 at 2:14
  • Can you share an minimal reproducible example? Where/when exactly is this middleware used? and what Express version are you using? Commented Apr 13 at 8:46
  • Are you just trying to set default query params? Then do something like req.query = Object.assign({limit: "5"}, req.query) as Middleware. Commented Apr 13 at 10:06

2 Answers 2

2

Answer: In latest version of express (v5) req.query is changed to be a getter so I guess it is immutable now, I remember I have been using express 4 for my previous project which for that version req.query is still mutable.

The solution I found is to mutate req.url instead which reflect the changes made in it to req.query

Sign up to request clarification or add additional context in comments.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0
exports.aliasData = (req, res, next) => {
  const query = new URLSearchParams(req.query);
  query.set('fields', 'title,description,instructor');

  // Rebuild the URL so Express reparses req.query
  req.url = `${req.path}?${query.toString()}`;

  console.log('aliasData triggered:', req.url); // optional debug
  next();
};

This is how we shoud do now,we got to reparse the url using built-in javascript class that allow you to reaad,create and manipulate URL query string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.