URL 作为 Express 中的参数

URL as parameter in Express

在 Express 中使用 Node.js,如何接受 URL 作为参数?

http://example.com/site/http%3A%2F%2Fgoogle.com

我有以下处理程序

app.get('/site/:dest', function (req, res, next) {
   res.end('URL = ' + req.params.dest);
});

我没有得到预期的响应,而是收到了 404:

The requested URL /site/http://www.google.com was not found on this server.

如果我请求示例。com/site/hello 它工作正常,但不适用于传递 URL。我假设它的正斜杠转义导致了问题。

有正确的方法吗?

您需要对参数的 URL 进行编码。如果您只是将 URL 作为参数发送,您将遇到很多问题。

最好的方法是 url encode 参数,在你的 nodejs 端你需要 url decode

示例: https://www.google.com 将是 https%3A%2F%2Fwww.google.com

解决方法如下:

更改了路由,现在使用 req.query

app.get('/', function (req, res, next) {
   res.end('URL = ' + req.query['site']);
});

现在,http://example.com/?site=http%3A%2F%2Fexample.com%2F%3Fhello%3Dworld%26foo%3Dbar 按预期工作。

对我有用

app.get('/site/*', function (req, res, next) {
  res.end('URL = ' + req.params[0]);
});