【问题标题】:Nodejs express regex routing with variable in it - why does not match?Nodejs 表达带有变量的正则表达式路由 - 为什么不匹配?
【发布时间】:2018-07-24 20:24:57
【问题描述】:

我正在使用 express 4.16,并且我想创建一个路由,该路由接受最后带有变量的每条路径。

我试过这样的东西,但它不匹配:S

 ...
    router.get('/.*:name$/', (req, res) => {
    ...

例如:

.../animal/Joe
.../fruit/apple.txt
.../people/man/Sam

我用这个页面来测试它: http://forbeslindesay.github.io/express-route-tester/

编辑 1 ----------------- 所以正如我提到的,我正在尝试创建一个 svg api,它以不同的颜色返回一个公共 svg 文件。示例:localhost:3000/svg/logo/logo.svg?color=#232323

server.js:

..
const svg = require('./server/routes/svg');
...
app.use('/svg', svg);
...

svg.js

const express = require('express');
const router  = express.Router();
var   fs      = require('fs');

router.get('/.*:name$/', (req, res) => {
    let name  = req.params.name;
    let color = req.query.color;
    console.log(req.path, color, req.originalUrl, req.path);
    if(typeof name != 'undefined' && typeof color != 'undefined'){
        res.setHeader('Content-Type', 'image/svg+xml');
        //                  here I should concatenate req.path before name or something like this idk..
        let read = fs.readFile(`${__dirname}/../../dist/assets/images/svg/${name}.svg`, 'utf8', (err, template) => {
            if(typeof template !== 'undefined'){
                let svg = template.replace(/\#000000/g, (match) => {
                    return color;
                });
                return res.send(svg);
            }else{
                return res.status(404).send();
            }
        });
    }else{
        return res.status(404).send();
    }
});

module.exports = router;

(这段代码不完整,我只是卡在路由器上)

提前感谢您的时间! :)

【问题讨论】:

  • 从你的问题中不清楚你想要匹配什么以及你期望捕获什么参数。
  • 我想创建一个 api,它根据 localhost:3000/svg/pathWhereICanFindThisFile/icon.svg?color=#232323 之类的路径返回 svg 文件,以便我可以读取 svg 修改其颜色并返回它作为回应。我只是想缩小我的问题:)
  • 如果你要让随机的网络用户像那样遍历你的目录,那就太危险了。
  • 您能解释一下原因吗?如果路径或颜色参数末尾没有 svg 名称,我将返回一个空 svg。另一方面,使用正确的路径、文件名和有效颜色,我返回一个具有不同颜色的公共文件。我认为这不会很危险
  • 但是我猜这个页面和他的可下载 svgs flaticon.com 非常相似(不确定)

标签: node.js regex express


【解决方案1】:

在玩了Express Route Tester之后,我想出了这个模式:

*/:name

根据 Route Tester,此模式将被编译(对 path-to-regexp 0.1.7 有效)为以下正则表达式:

/^(.*)\/(?:([^\/]+?))\/?$/i

^(.*) 将从一开始就捕获所有内容

([^\/]+?) 将捕获最后一个值并将其存储到name

注意:注意*被编译为(.*)很重要。

对于最新版本的 path-to-regexp,以下模式应该是等效的:

(.*)/:name

希望对你有帮助!

【讨论】:

  • 我的英雄!非常感谢您和其他人的时间:)
【解决方案2】:

根据我更好的判断,您可以使用未命名的正则表达式来做您正在寻找的事情。

router.get('/svg/path/(.*)', (req, res) => {
  // in here, you'll get the full path with req.path and then parse it validate it's the right form and to get the info you need out of it.

  // You can also use req.query to get the color param you mentioned.  
});

【讨论】:

  • 这个路由器讨厌我。仍然不匹配:(
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 2015-07-06
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
  • 2011-11-05
相关资源
最近更新 更多