我是javascript的新手。我尝试使用Node.js和Express.js
创建RESTfull API我的目录结构如下
/server.js
/api/api.js
/api/location/location.js
我想让API模块化。我希望以/api/*
开头的所有请求(get / post / delete / push)由 api.js 处理,无论需要什么路由, api.js 应该将其路由到适当的模块。
例如,如果有人请求GET /api/location/abc/xyz
,则api.js
会将控件转移到location.js
,然后转移到abc.js
,最终会转移到xyz.js
存储在目录 /api/location/abc/xyz/xyz.js
我怎样才能做到这一点?
到目前为止var express = require('express');
var app = express();
var api = require('./api/api.js');
var location = require('./api/location/location.js');
//app.use('/api/location', location); //This works, but I want api.js to handle sub-routes!
app.use('/api', api);
app.get('/', function(req, res){
res.end('successful get/');
});
app.listen(12345);
module.exports = function(req, res, next) {
res.end('successful get /api');
next();
};
//Add code to handle GET /api/location
module.exports = function(req, res, next){
res.end('from location!');
next();
}
答案 0 :(得分:1)
您可以使用express.Router([options])
。
然后这样写:
<强> /api/api.js 强>
var router = require('express').Router();
router.get('/location', require('./api/location') );
module.exports = router;
<强> /api/api/location.js 强>
module.exports = function(req, res, next){
res.end('from location!');
}
如果您结束了回复,请不要致电next();
。如果您不处理响应,则只能在回调中调用next()
。
我不知道你的REST api稍后会有多复杂。但是尝试将路由保留在少量文件中。在像/api/api/location.js
这样的自己的文件中回调路由很可能不是最好的主意。