使用Express.js与Node.js进行多级路由

时间:2016-02-27 16:28:56

标签: javascript node.js api express

我是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

我怎样才能做到这一点?

到目前为止

代码:

/server.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);

/api/api.js

module.exports = function(req, res, next) {
    res.end('successful get /api');
    next();
};

//Add code to handle GET /api/location

/api/location/location.js

module.exports = function(req, res, next){
    res.end('from location!');
    next();
}

1 个答案:

答案 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这样的自己的文件中回调路由很可能不是最好的主意。