我目前正在构建一个小型express驱动的节点应用程序,以支持RESTful API,从我编写的节点模块中暴露数据。模块中的一个函数接受三个参数,但我想通过指定一个、两个、另外两个或全部三个参数来允许使用API。
所以即使是开始这样写路由已经感觉很荒谬了。
app.get('/api/monitor/:stop/:numresults', apiController.monitorNum);
app.get('/api/monitor/:stop/:timeoffset', apiController.monitorOff);
app.get('/api/monitor/:stop', apiController.monitor);
特别是因为我不知道如何指定前两者之间的差异,因为numresults和timeoffset都只是整数。
这种情况下的最佳实践是什么样子的?
您面临的第一个问题是您有相同的路由,如果您使用express(我假设您正在使用express),这是不可能的。相反,您可能需要一个路由并使用查询对象:
app.get('/api/monitor/:stop/', function (req, res, next) {
var stop = req.params.stop,
numResults = req.query.numResults,
timeOffset = req.query.timeOffset;
yourFunc(stop, numResults, timeOffset);
});
这样你就可以用以下url调用api: http://example.com/api/monitor/somethingAboutStop/?numResults=1&timeOffset=2
。看起来stop参数也可以移动到查询对象中,但这取决于您。
你可以使用一个全局路由,然后自己解析它。
的例子:
app.get('/api/monitor/*', apiController.monitor);
然后在apiController。Monitor你可以进一步解析url:
exports.monitor = function(req, res) {
var parts = req.url.split('/');
console.log(parts); // [ '', 'api', 'monitor', '32', 'time' ]
console.log(parts.length); // 5
res.end();
};
所以,点击/api/monitor/32/time,你就得到了上面的数组。点击/api/monitor/something/very/long/which/you/can/parse,你就可以看到你的每个参数都去了哪里。
或者你可以自己动手,比如/api/monitor/page/32/offset/24/maxresults/14/limit/11/filter/by-user
虽然,正如Deif已经告诉你的那样,你通常使用查询参数,maxResults &