gpt4 book ai didi

node.js - 在 Node js 中将 URL 作为查询参数传递

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:10 25 4
gpt4 key购买 nike

我正在尝试从浏览器访问 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 作为查询参数?

最佳答案

您需要先使用 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

关于node.js - 在 Node js 中将 URL 作为查询参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com