首页 > 解决方案 > 如何在路由中获取完整的 url 作为参数

问题描述

我需要获取完整的 url 作为参数以将其转换为 qrcode。一旦网址采用这种格式https://website.com.br/2k,我就无法在我的 node.js 路由中将其作为参数接收

这就是我将参数发送到 ejs 页面的方式

res.render("tutorial.ejs", { qrcode: '/qrcode/'+ link });

link是这样的:http://comp.co/32

在 tutorial.ejs 中,我渲染了调用 qrcode 路由的 qrcode

 <img src="<%= qrcode %>">

二维码路线:

routes.get('/qrcode/:url',(req,res, next) => {    
    const code = qr.image(req.params.url, {type: 'svg'});
    res.type('svg');
    code.pipe(res);
})

它不工作。我认为发生这种情况是因为我的 qrcode 路由得到了这样的参数:http://comp.co/32

标签: node.jsejs

解决方案


当你提出请求时,你基本上是在打电话

routes.get(/qrcode/http:/comp.co/32){...} 

所以后端的路由器将其理解为路由,它不会调用您的预期路由,即
routes.get(/qrcode/:url){...}

解决方案:

网址将您的网址编码为并再次尝试您的代码。

var link="http%3A%2F%2Fcomp.co%2F32"
res.render("tutorial.ejs", { qrcode: '/qrcode/'+ link });

<img src="<%= qrcode %>">

routes.get('/qrcode/:url',(req,res, next) => {    
    const code = qr.image(req.params.url, {type: 'svg'});
    res.type('svg');
    code.pipe(res);
})

但是传递参数的更好方法是使用查询来避免混淆,你可以这样做

res.render("tutorial.ejs", { qrcode: '/qrcode?url='+ link });


routes.get('/qrcode',(req,res, next) => {    
    const code = qr.image(req.query.url, {type: 'svg'});
    res.type('svg');
    code.pipe(res);
})

希望它能解决你的问题。


推荐阅读