简体   繁体   中英

Given a controller function or route path, how do I get the full route URL in Express JS?

I am writing an Express JS application and I need to calculate a route given a controller function or route path.

For example:

 let myUrl = functionToGetRoutePath(ThingsController.getThing); // would return https://host/api/v1/things/{id} // Or let myUrl = functionToGetRoutePath('/things/{id}'); // would return https://host/api/v1/things/{id} 

Or, given parameters, it could fill in the URL parameters, for example:

 let myUrl = functionToGetRoutePath(ThingsController.getThing, { id: 1 }); // would return https://host/api/v1/things/1 // Or let myUrl = functionToGetRoutePath('/things/{id}', { id: 1 }); // would return https://host/api/v1/things/1 

Coming from .NET, this is pretty easy using UrlHelper:

new UrlHelper(Request).Link("Things Route Name", new { id = 1 }); // returns https://host/api/v1/things/1

req.originalUrl在这方面有帮助吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM