Ava Juan
Ava Juan

Reputation: 113

Query String missing when redirecting with expressjs

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.

Upvotes: 1

Views: 794

Answers (1)

Tyler2P
Tyler2P

Reputation: 2370

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

Upvotes: 1

Related Questions