怎么把express写的接口放进单独的文件。

用express实例化一个app对象
图片描述

然后我想将这样的代码写进一个单独的js文件,作为一个模块,但是会报找不到app对象的错
图片描述

想问下我应该怎么模块化管理自己的接口

阅读 3.4k
4 个回答

单独放入文件夹的话,如果你使用了app.use你还是需要在你的api文件夹里面声明app

在原本的js用export 把app export出去,在新的js用require 提取取來

推荐使用对应的route

// invoked for any requests passed to this router
router.use(function(req, res, next) {
  // .. some logic here .. like any other middleware
  next();
});

// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
  // ..
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题