Javascript 使用Node.js从URL捕获参数
我有一个固定的链接,如下所示:Javascript 使用Node.js从URL捕获参数,javascript,node.js,url,parameters,Javascript,Node.js,Url,Parameters,我有一个固定的链接,如下所示: http://link.com/?val1=val1&val2=val2 这个链接将我重定向到一个新的链接,该链接的随机值为常量参数,如: http://link2.com/?constant=randomvalue/ 每次使用第一个链接时,我都会从下面的链接中获得一个随机值 通过使用Node.js,我如何在第二个链接中捕捉“constant”的“randomvalue” 我必须使用第一个链接才能到达第二个链接。@Misantorp的答案可能是最好的,
http://link.com/?val1=val1&val2=val2
这个链接将我重定向到一个新的链接,该链接的随机值为常量参数,如:
http://link2.com/?constant=randomvalue/
每次使用第一个链接时,我都会从下面的链接中获得一个随机值
通过使用Node.js,我如何在第二个链接中捕捉“constant”的“randomvalue”
我必须使用第一个链接才能到达第二个链接。@Misantorp的答案可能是最好的,但还有另一种方法。查看内置于Node中的querystring模块,它有一种方便的解析方法,只适用于以下情况: 这应该起作用:
const querystring = require('querystring');
querystring.parse("http://link2.com/?constant=randomvalue/"); // { 'http://link2.com/?constant': 'randomvalue/' }
您可能希望从?
开始使用子字符串,以使其更加清晰:
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"]);
}
尝试将第二个链接作为URL读取
let secondURL = new URL("http://link2.com/?constant=randomvalue/");
然后像这样提取常量的值
let constantValue = secondURL.searchParams.get("constant"); //"randomvalue/"
但是我必须使用第一个链接才能到达第二个链接,因此直接到达第二个链接没有任何意义,因为随机值将保持不变。然后你可能应该用一个你想要实现的示例更新你的问题