【问题标题】:How to pass URL as parameter with another URL?如何将 URL 作为参数传递给另一个 URL?
【发布时间】:2017-08-06 05:51:02
【问题描述】:

我有这条路线/new/:url。现在,当我提出像/new/https://www.google.com 这样的请求时,我得到Cannot GET /new/https://www.google.com 作为响应。我期望得到字符串https://www.google.com。我读了这个关于编码 URL 的答案URL component encoding in Node.js,但是当GET 请求路由/new/:url 时,我将如何做到这一点?这是我的那条路线的代码

app.get('/new/:url',(req,res) => {
  const url = encodeURIComponent(req.params.url);
  console.log(url);
  res.json({
    url
  });
});

【问题讨论】:

    标签: javascript node.js express url


    【解决方案1】:

    你可以用wildcard路由尝试这种方式,未经测试,但应该可以工作

    app.get('/new/*',(req,res) => {
      const url_param = req.params[0];
      const url = req.hostname;
      console.log(url,url_param);
      res.json({
        url
      });
    });
    

    req.params[0] 将为您提供http://www.yourapp.com/new/https://www.google.comhttps://www.google.com 部分和 req.hostname 会给你原来的http://www.yourapp.com/

    【讨论】:

    • 这行得通。但我不明白为什么我的路由处理程序不起作用?此方法也不会对 URL 进行编码,那么为什么它不将 https://www.google.com 中的 / 视为 url 的单独部分并破坏响应。
    • 这可能有效,但每个参数都应在作为 url 组件传输时进行编码。
    【解决方案2】:

    你必须路由到一个编码的 url。在您的路由器回调函数中,您应该解码 url 组件。

    app.get('/new/:url',(req,res) => {
       const url = decodeURIComponent(req.params.url);
       console.log(url);
       res.json({
         url
       });
     });
    

    你链接到这个/new部分的部分应该encodeURIComponent()传递的url。

    编码后的网址应类似于/new/http%3A%2F%2Fgoogle.de

    前端部分:

    const baseUrl = '/new';
    const urlParameter = 'http://example.com';
    const targetUrl = `${baseUrl}/${encodeUriComponent(urlParameter)}`;
    const method = 'GET';
    
    const xhr = new XMLHttpRequest();
    xhr.open(method,targetUrl);
    xhr.onload = () => {
    
        const jsonCallback = JSON.parse(xhr.response);
    }
    
    xhr.send();
    

    【讨论】:

    • 你使用前端框架吗?由于后端库是快速的(我认为)前端应该完成这项工作。我将编辑我的答案以提供一个非框架示例。
    猜你喜欢
    • 2015-02-12
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多