我不太确定该给它起什么标题,但我是 Node.js
的新手。我刚刚在 GitHub 上找到了一个简洁的 REST API 项目来实现,但我不确定如何将所有 GET 和 POST 等拆分为单独的文件。
我有一个单一的 api.js
文件
function API_ROUTER(router, connection, md5) {
var self = this;
self.handleRoutes(router, connection, md5);
}
API_ROUTER.prototype.handleRoutes = function(router, connection, md5) {
router.get("/", function(req, res) {
res.json({"Message" : "Hello World !"});
});
};
module.exports = API_ROUTER;
现在我如何创建同级 other.js
并使用:
var api = require('./api.js');
// Create router.get, router.post etc. here?
最佳答案
but I'm not sure how I can split all GET and POST etc. to separate files.
组织路由的一种方法是为每个路由创建一个单独的对象,其中包含处理程序(由 HTTP 方法分隔)和其他所需信息,例如路径:
api/home.js
module.exports = {
path: '/',
handlers: {
'get': function(req, res) {
res.json({"Message" : "Hello World !"});
},
'post': {
// ...
}
// ...
}
}
api/other.js
module.exports = {
path: '/other',
handlers: {
'get': function(req, res) {
res.json({"Message" : "Other !"});
},
// ...
然后您可以在 handleRoutes
方法中加载所有这些内容:
API_ROUTER.prototype.handleRoutes = function(router, connection, md5) {
var routes = ['home', 'other'];
routes.forEach(function(name) {
// load the current route object (NOTE: you should use the path module for determining file path in a cross-platform manner)
var routeObject = require('./' + name + '.js');
var apiPath = routeObject.path;
var handlers = routeObject.handlers;
var methods = Object.keys(handlers);
// assign handlers for each method
methods.forEach(function(method) {
router[method](apiPath, handlers[method]);
});
});
};
这将安装您的所有路由以及适当的信息和处理程序。
现在,您可以通过使用必要的数据实例化 API_ROUTER
来调用此代码:
// initialize the api (and handle the routes internally)
var Api = new require('./api.js')(router, connection, md5);
关于javascript - Node.js API 设计和路由处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36382232/