将URL作为节点js中的查询参数传递

时间:2019-07-23 02:17:08

标签: node.js query-parameters

我正在尝试从浏览器中访问URL http://localhost:3000/analyze/imageurl=https://www.google.com/

但是,由于存在//,它无法正确访问URL,并给我一个错误消息Cannot GET /analyze/imageurl=https://www.google.com/

如果我摆脱了如下http://localhost:3000/analyze/imageurl=httpswww.google.com/的反引号,则它确实可以正常工作。

我的后端API看起来像这样

app.get('/analyze/:imageurl', function (req, res) {
 console.log('printing image url:' + req.params.imageurl);
}

有没有一种方法可以传递带有反引号作为查询参数的imageurl

2 个答案:

答案 0 :(得分:0)

您需要先使用encodeURIComponent对URL进行编码,然后再将其传递给查询字符串。例如:

var urlParam = encodeURIComponent('https://www.google.com/');
console.log(urlParam); // https%3A%2F%2Fwww.google.com%2F
var url = 'http://localhost:3000/analyze/' + urlParam;
console.log(url); // http://localhost:3000/analyze/https%3A%2F%2Fwww.google.com%2F

// Decode it in API handler
console.log(decodeURIComponent(urlParam)); // https://www.google.com/

encodeURIComponent

答案 1 :(得分:0)

一种方法可能是在您的路线中使用Express'req.query。看起来像这样:

// Client makes a request to server
fetch('http://localhost:3000/analyze?imageurl=https://google.com')
// You are able to receive the value of specified parameter 
// from req.query.<your_parameter>
app.get('/analyze', (req, res, next) => {
    res.json(req.query.imageurl)
})
相关问题