7

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?

1 Answer 1

12

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.

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

4 Comments

Out of curiosity, could he not also just update the req.query object within his middleware ? req.query={id: 'someID', product: 'bag"}
@wlh duh, of course that's also possible, and much easier too! :D
How do I do the same thing with post? server.post("/sample-redirect", (req, res) => { res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, application/json" ); res.header( "Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS" ); console.log("Request Data : ", req.body); return app.render(req, res, "/sample-redirect", { sample_data: req.body }); });
I would like to append the posted data to the URL like /sample-redirect?JSON.stringify(sample_data)

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.