繁体   English   中英

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

[英]Multiple level of routing using Express.js with Node.js

我是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/xyzapi.js会将控制权转移到location.js ,然后将其转移到abc.js ,最终将转移到存储在目录 /api/location/abc/xyz/xyz.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();
}

您将使用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为路由进行回调很可能不是最好的主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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