如何获得一个url作为Node.js中的参数?

码:

app.get("/:url", function(req,res) { var url = req.params.url; res.send(url); }); 

问题:

这不起作用。

如果我尝试:

 http://localhost:3000/https://www.google.com 

我得到:

 Cannot GET /https://www.google.com 

你可以试试这个,使用正则expression式:

 var app = require('express')(); app.get(/^\/(.*)/, function (req, res) { var url = req.params[0]; res.send(url); }); app.listen(3000, () => console.log('Listening on 3000')); 

当你运行:

 curl http://localhost:3000/https://www.google.com 

服务器应该返回:

 https://www.google.com 

更新

关于冒号在URL中是否合法存在争议。

看到这个问题的细节:

  • URL中是否允许冒号?

根据RFC 3986,这是一个合法的URL:

 http://localhost:3000/https://tools.ietf.org/html/rfc3986 

但请注意,虽然这也是合法的:

 http://localhost:3000/https://tools.ietf.org/html/rfc3986#section-3.3 

如果您在浏览器中input了该url,则您的服务器只会获得:

 /https://tools.ietf.org/html/rfc3986 

在请求中。 由于这个原因,虽然不是绝对必要的,我仍然会推荐使用URL来编码您在其他url中input的url – 请参阅Zac Delventhal的答案。

实验

使用上面的代码示例,这个命令:

 curl http://localhost:3000/https://www.google.com/ 

会输出这个:

 https://www.google.com/ 

但是这个命令:

 curl 'http://localhost:3000/https://www.google.com/#fragment' 

会输出这个:

 https://www.google.com/ 

请注意,我使用上面的单引号不是因为他们在这里是必要的 – 他们不是,看到这个:

 echo http://localhost:3000/https://www.google.com/#fragment 

而是为了显示哈希片段不会消失,因为它被shell视为一个注释,以防有人认为这可能是原因。 即使使用引号也不会发送,而发生的事情可以用curl-v开关来演示:

 * Connected to localhost (127.0.0.1) port 3000 (#0) > GET /https://www.google.com/ HTTP/1.1 > User-Agent: curl/7.35.0 > Host: localhost:3000 > Accept: */* 

正如你所看到的哈希片段甚至没有发送HTTP,所以你的服务器甚至不可能知道它存在。

顺便说一下,这也表明,在其他URL中使用未编码的URL不会混淆任何代理,因为对代理服务器的HTTP请求会发送:

 GET https://www.google.com/ HTTP/1.1 

而不是这个:

 GET /https://www.google.com/ HTTP/1.1 

所以他们不能混淆。 (注意斜杠。)

这是因为:/是用于构buildURL的特殊字符。 换句话说,它们不是url安全的 。 如果要将这些字符作为URLpath的一部分发送,则使用默认的Express paramparsing器,则必须对它们进行百分比编码 。

试试这个与你现有的代码:

 curl http://localhost:3000/https%3A%2F%2Fwww.google.com 

你应该回来:

 https://www.google.com 

另一个select是使用查询参数而不是pathvariables。 稍微修改你的代码片段:

 app.get("*", function(req, res) { var url = req.query.url; res.send(url); }); 

然后,你可以用这个命令testing它:

 curl http://localhost:3000?url=https://www.google.com 

你应该回来:

 https://www.google.com 

尽pipe如此,尽pipeExpress可以用这种方式来parsing,但对这些字符进行百分比编码仍然是一个好主意。 这可能会导致在路上的怪异行为。

还有一个select是将URL作为POST请求正文中的string发送,但根据您的使用情况,这可能不是RESTful。