我有以下代码。它允许我获取图像,并可选择指定是否需要重新缓存。例如,/something.jpg/force
。它也可以是图像的 ID,例如 /7GDF4G
。如您所见,力参数是可选的。
app.get('/:image/:force?*', function (req, res) {
console.log("image req");
// Create variable to hold force bool, default is false
var force = false;
// Check if force bool is present
if (req.params.force === ('force' || 'true' || 'recache' || 're-cache')) {
force = true;
}
// Pass req, res, image variable and force bool to process
mod.request.process({
req : req,
res : res
}, {
type : 'image',
id : req.params.image
}, force);
});
运行时,所有内容都会按预期传递到 mod.request.process()
上。但是,如果我添加以下内容来查看 :image
返回什么值:
console.log(JSON.stringify(data));
这是记录的内容:
{"type":"image","id":"k"}
输入的 URL 为 kMoI9Vn.jpg/force
,因此 id
应为 kMoI9Vn.jpg
。如果我使用 something.jpg
再次运行它,我会得到 {"type":"image","id":"s"}
。
关于为什么会发生这种情况有什么想法吗?
最佳答案
为什么不直接删除星号并仅使用 /:image/:force?
?
这适用于两个示例:
var pathToRegexp = require('path-to-regexp');
var keys = [];
var exp = pathToRegexp('/:image/:force?', keys);
console.dir(exp.exec('/7GDF4G'));
console.dir(exp.exec('/something.jpg/force'));
// outputs:
// [ '/something.jpg/force',
// 'something.jpg',
// 'force',
// index: 0,
// input: '/something.jpg/force' ]
// [ '/7GDF4G', '7GDF4G', undefined, index: 0, input: '/7GDF4G' ]
关于javascript - 路由参数仅获取第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25364869/