koa router 多文件引入的方法示例
èæ¯
koa-routerè·¯ç±è¶æ¥è¶å¤,apiä¸çrouteré½è¦ä½¿ç¨ä¸é¢çæ¹å¼å¼å¥,æä¹æè½æ¹ä¾¿å¿«æ·çå°apiä¸çæææ件é½å¼å¥å¢
è¿æ¬¡è®°å½çå°±æ¯å¦æå°koa-router ä¸æ¬¡æ§å¾ªç¯å¼å¥
const book = require('./app/api/v1/book') const classic = require('./app/api/v1/classic') // ... app.use(book.routes(), book.allowedMethods()) app.use(classic.routes(), classic.allowedMethods()) //...
æ件ç®å½
koa-demo/ |-api/ |-books.js |-classic.js |-users.js |-articles.js |-package.json |-app.js
ä¼ ç»æ¹å¼å¼å¥router
app.js
const Koa = require('koa') const app = new Koa() const book = require('./app/api/v1/book') const classic = require('./app/api/v1/classic') app.use(book.routes(), book.allowedMethods()) app.use(classic.routes(), classic.allowedMethods()) app.listen(3333)
require-directoryå¼å¥
require-directoryç¨æ¥éå½å°è¿ä»£æå®çç®å½ï¼å¹¶è¿åè¿äºæ¨¡åã
éçæ件å¢å ï¼å¦ä½é«æçå¼åå°±æ¯æ们è¦è¿½æ±çäºæäº
é¦å
npm install require-directory
app.js
const Koa = require('koa') const app = new Koa() const Router = require('koa-router') // 使ç¨require-directoryå 载路ç±æ件夹ä¸çæærouter const requireDirectory = require('require-directory') // å°ææçè·¯ç±å è½½ä¸,èªå¨å 载代ç const modules = requireDirectory(module, './api', { visit: whenLoadModule }) function whenLoadModule(obj) { if (obj instanceof Router) { app.use(obj.routes(), obj.allowedMethods()) } } app.listen(3333)
è·¯ç±æ件就æç§ä¼ ç»çæ¹å¼åå°±è¡
books.js
const Router = require('koa-router') const router = new Router() router.get('/v1/book/latest', (ctx, next) => { ctx.body = { key: 'book' } }) module.exports = router
以ä¸å°±æ¯æ¬æçå¨é¨å容ï¼å¸æ对大家çå¦ä¹ ææ帮å©ï¼ä¹å¸æ大家å¤å¤æ¯æèæ¬ä¹å®¶ã
相关推荐
webgm 2020-08-16
yezitoo 2020-06-06
始作俑者 2020-01-19
Qimingweikun 2019-11-04
LorenLiu 2019-11-04
oSweetBear 2019-11-04
lei0 2020-11-02
igogo00 2020-07-04
iconhot 2020-06-26
88481456 2020-06-18
疯狂紫萧 2020-06-16
SelinaChan 2020-05-15
luckymaoyy 2020-04-25
80437700 2020-04-17
austindev 2020-04-07
我有一只小松鼠 2020-02-29
webfullStack 2020-02-15
binglingnew 2012-10-03