我试图在Express中将一些路由及其处理程序逻辑拆分为单独的文件.我已经看到了类似于JS的示例目录结构,其中使用了单独的路由和控制器文件,因此我试图实现这种方法但是遇到了问题.
我的服务器和路由配置如下:
server.js
var express = require('express'), app = express(), bodyParser = require('body-parser'), routes = require('./routes/index') app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); routes(app);
/routes/index.js
module.exports = function(app) { var catalogues = require('../routes/catalogues'); app.use('/catalogues-api', catalogues); };
/routes/catalogues.js
var catalogues = require('../controllers/catalogues'); module.exports = function(app) { app.route('/catalogues') .get(catalogues.apiGET) .post(catalogues.apiPOST); };
/controllers/catalogues.js
var request = require('request'); exports.apiGET = function(req, res) { var options = prepareCataloguesAPIHeaders(req); request(options, function(err, response, body){ res.send(body); }); }; exports.apiPOST = function(req, res) { var options = prepareCataloguesAPIHeaders(req); options.json = true; options.body = stripBody(req.body); request(options, function(err, response, body){ res.send(body); }); };
运行应用程序并对/ catalogs-api/catalogs发出GET请求时,我从节点抛出一个错误:
TypeError:undefined不是module.exports的函数(C:\ Users\rparker\Documents\GitHub\testproj\src\server\routes\catalogues.js:4:7)
这是在我的/routes/catalogues.js文件中引用app.route声明.我在设置中显然遗漏了一些东西,但我无法理解.
有人可以帮忙吗?谢谢
在/routes/catalogues.js
var express = require('express'); var router = express.Router(); var catalogues = require('../controllers/catalogues'); router.route('/catalogues') .get(catalogues.apiGET) .post(catalogues.apiPOST); module.exports = router;
查看本文档的最后一部分