Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a query string to req.url in Express?

I want to add a string to a req.url in Express. The string looks like this:

?id=someID&product=bag

I don't have an access to client html or server. All I get from client it's just a GET request without any parameters. So I tried to make middleware which would add query string and then I will parse it like always. The idea was:

// Middleware

const addQuery = (req, res, next) => {
    req.url = req.url + `?id=someID&product=bag`;
    next();
}

And then in request handler:

router.get('/', addQuery, (req, res) => {
    console.log(req.query.id);
    console.log(req.query.product);
});

But it gives me undefined. I can't use any client side js and I can't use server side coding. Not my origin sends me this request.

So how to add query string to express request and then successfully parse it?

like image 358
Nastro Avatar asked Nov 08 '18 20:11

Nastro


1 Answers

express appears to export a middleware called query that it uses to parse query strings. Because this middleware is typically called early in the request flow, adding a query string to req.url happens "too late".

Here's a workaround that appears to work:

const addQuery = (req, res, next) => {
  req.url   = req.url + `?id=someID&product=bag`;
  req.query = null; // if this isn't added, the `query` middleware
                    // will assume the query string is already parsed
  next();
}

app.get('/', addQuery, express.query(), (req, res) => {
  ...
});

EDIT: as @wlh rightfully suggests, addQuery could also modify req.query directly:

const addQuery = (req, res, next) => {
  req.query.id      = 'someID';
  req.query.product = 'bag';
  next();
}

This should work pretty much the same, but much cleaner.

like image 78
robertklep Avatar answered Sep 30 '22 05:09

robertklep