uhbc
uhbc

Reputation: 84

Catching a param from URL by using Node.js

I have a constant link looking like this:

http://link.com/?val1=val1&val2=val2

And this link redirects me to a new link with a random value of a constant param such like;

http://link2.com/?constant=randomvalue/

Each time I use the first link, I get a random value from the following link.

By using Node.js, how can I catch the 'randomvalue' of 'constant' in the second link?

I have to use the first link to reach the second one.

Upvotes: 0

Views: 60

Answers (2)

icdevin
icdevin

Reputation: 144

@Misantorp's answer is probably best, but there is another way to do it. Check out the querystring module built into Node, it has a convenient parse method just for things like this: https://nodejs.org/api/querystring.html

This should work:

const querystring = require('querystring');

querystring.parse("http://link2.com/?constant=randomvalue/"); // { 'http://link2.com/?constant': 'randomvalue/' }

You may want to substring from the ? onwards to make it more clear:

const str = "http://link2.com/?constant=randomvalue/";
const paramIndex = str.indexOf("?");
if (paramIndex >= 0) {
    const queryParamStr = str.substr(str.indexOf("?"));
    const queryParams = querystring.parse(queryParamStr);
    console.log(queryParams["constant"]);
}

Upvotes: 0

Misantorp
Misantorp

Reputation: 2821

Try reading the second link as a URL

let secondURL = new URL("http://link2.com/?constant=randomvalue/");

Then extract the value of the constant searchparam like so

let constantValue = secondURL.searchParams.get("constant"); //"randomvalue/"

Upvotes: 1

Related Questions