Query String missing when redirecting with expressjs

Issue

I have the following express js route which helps in redirecting to the given URL.

app.get("/", async (req, res) => {
  const url = req.query.url;
  res.redirect(url);
});

It’s working fine. But the problem is, somehow the passed query strings is getting cut off for no reason.

Example:

This is what I’m actually passing.

http://localhost:3000/?url=https://google.com/?abc=123&def=456&aaa=098

After redirecting whatever after the first query string goes missing.

It’s appearing like this.

https://google.com/?abc=123

Not sure why &def=456&aaa=098 goes missing.

Solution

Use the encodeURIComponent and decodeURIComponent functions.

For example:

app.get("/", async (req, res) => {
  const url = req.query.url;
  res.redirect(decodeURIComponent(url));
});

Note that the url parameter must be encoded in the actual URL.
Your URL should look something like this:

http://localhost:3000/?url=https://google.com/%3Fabc%3D123%26def%3D456%26aaa%3D098

Answered By – Tyler2P

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