繁体   English   中英

使用Node.js从URL捕获参数

[英]Catching a param from URL by using Node.js

我有一个不变的链接,看起来像这样:

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

并且此链接将我重定向到一个具有常量参数的随机值的新链接,例如;

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

每次使用第一个链接时,都会从以下链接中获得随机值。

通过使用Node.js,如何在第二个链接中捕获“常量”的“随机值”?

我必须使用第一个链接才能到达第二个链接。

尝试读取第二个链接作为URL

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

然后像这样提取constant searchparam的值

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

@Misantorp的答案可能是最好的,但是还有另一种方法。 签出Node内置的querystring模块,它具有一个方便的解析方法,仅用于以下目的: https : //nodejs.org/api/querystring.html

这应该工作:

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"]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM