2017-08-06 270 views
0

我有这条路线/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,但是如果对路由/new/:url发出GET请求,我怎么能这样做呢?这是我的路线代码如何将URL作为参数传递给另一个URL?

app.get('/new/:url',(req,res) => { 
    const url = encodeURIComponent(req.params.url); 
    console.log(url); 
    res.json({ 
    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]会给你https://www.google.com部分的http://www.yourapp.com/new/https://www.google.comreq.hostname会给你原来的http://www.yourapp.com/

+0

这有效。但我不明白为什么我的路由处理程序不起作用?这种方法也不会对URL进行编码,那么为什么它不会将'https:// www.google.com'中的'/'作为url的单独部分并打破响应。 –

+0

这可能会起作用,但每个参数都应该在作为url组件进行传输时进行编码。 – Wartoshika

0

您必须路由到编码的网址。在你的路由器回调函数中,你应该解码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(); 
+0

我该怎么做?你能举一个例子吗? –

+0

你使用前端框架吗?由于后端库是明确的(我认为)前端应该完成这项工作。我编辑我的答案以提供非框架示例。 – Wartoshika