我使用的是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;
(此代码无法完成,我只是卡在路由器上)
提前感谢您的时间! :)
答案 0 :(得分:2)
在玩过Express Route Tester之后,我想到了这种模式:
*/:name
根据路由测试器,此模式将编译(对正则表达式路径0.1.7有效)为以下正则表达式:
/^(.*)\/(?:([^\/]+?))\/?$/i
^(.*)
将从头开始捕获所有内容
([^\/]+?)
将捕获最后一个值并将其存储到name
注意:观察*
已编译为(.*)
很重要。
对于最新版本的正则表达式路径,以下模式应等效:
(.*)/:name
希望有帮助!
答案 1 :(得分:0)
根据我更好的判断,您可以使用未命名的正则表达式来完成您要查找的内容。
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.
});