在Express.js中,如何设置路由名称,以便以后可以简单地调用该路由名称来检索相应的URL?
File app.ts:
app.use('/api', apiRouter);
File api.ts:
router.use('/auth', authRouter);
File auth.ts:
router.get('/login', AuthController.login).as('my route name');
or
app.get('/login', AuthController.login, name='my route name');
...
output:
res.send(anyFunction('my route name')) // => /api/auth/login | https://example.com/api/auth/login
任何示例或文档。谢谢
更新日期:2023年8月3日
虽然我对它并不完全满意(我最初的意图是找到一个像Laravel这样的完全自动化的解决方案),但我可以接受它
答案
.
route.url.ts
function replaceParams(urlReplace: string, params: { [key: string]: string } = {}): string {
const queryParams: { [key: string]: string } = { ...params };
const url: string = urlReplace.replace(/:([a-zA-Z0-9]+)(\(.+?\))?/g,
(match, paramName, regexPart) => {
delete queryParams[paramName];
const regex = regexPart ? new RegExp(regexPart.slice(1, -1)) : null;
return params[paramName] && (!regex || regex.test(params[paramName])) ? params[paramName].toString() : ':' + paramName;
});
const queryString: string = Object.keys(queryParams)
.map((key) => key + '=' + queryParams[key])
.join('&');
return queryString ? (url.includes('?') ? `${url}&${queryString}` : `${url}?${queryString}`) : url;
}
export default (routeName: string, params: { [key: string]: string } = {}): string => {
const appUrl: string = process.env.APP_URL || '';
switch (routeName) {
case 'api.a':
return replaceParams(`${appUrl}/api/a/:user_id`, params);
case 'api.b':
return replaceParams(`${appUrl}/api/b/:user_id([a-z0-9]+)`, params);
case 'api.c':
return replaceParams(`${appUrl}/api/c/`, params);
default:
return '';
}
};
app.ts
app.get('/', function (req, res){
res.json({
a: routeUrl('api.a', { user_id: 'user12321423432' }),
b: routeUrl('api.b', { user_id: 'user12321423432' }),
c: routeUrl('api.c', { user_id: 'user12321423432' })
});
});
输出
{"a":"http://127.0.0.1:8000/api/a/user12321423432","b":"http://127.0.0.1:8000/api/b/user12321423432","c":"http://127.0.0.1:8000/api/c/?user_id=user12321423432"}
我希望我能得到比这更好的东西