node.js - 如何在路由中获取完整的 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
解决方案
当你提出请求时,你基本上是在打电话
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);
})
希望它能解决你的问题。
推荐阅读
- magento2 - 如何在管理面板中修复“处理您的请求时出错 :: 指定无效的父 ID (Magento_Backend::mgs)”..?
- javascript - 将字符串从 laravel 控制器转换为 javascript
- angular - Visual Studio devops Angular 构建失败
- android - FrameManager 返回 NullPointer 异常
- python - 如何在 Python 中只允许列出最大数量的项目
- python - Django 发布数据未保存在管理数据库中
- objective-c - 如何将编码的 DER 证书转换为 NSString 格式?
- ios - 如何解决 UID 1 符号中有关 N_SO 的 LLDB 错误
- javascript - 选中复选框时启用/禁用输入
- python-3.x - TypeError:无法使用 haarcascade 在人脸检测中连接“str”和“int”对象