koa2提示router.xxx is not function
2020-05-01 07:45:35

我是使用koa2-generator应用生成器创建的,每次添加路由启动项目的时候就提示router.xxx is not function,这个问题是最近才遇到的,因为我更新了最新的版本,之前的路由都需要注册一下,现在呢是不需要多次注册的,只需要注册一次就好了。这个问题网上也很少资料,不知道是不是我搜索的方式不对。来上代码:
我的项目配置:

{
  "name": "koaapp",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "debug": "~4.1.1",
    "koa": "^2.11.0",
    "koa-bodyparser": "^4.3.0",
    "koa-convert": "^1.2.0",
    "koa-json": "^2.0.2",
    "koa-logger": "^3.2.1",
    "koa-onerror": "^4.1.0",
    "koa-router": "^8.0.8",
    "koa-static": "^5.0.0",
    "koa-views": "^6.2.1",
    "nunjucks": "~3.2.1",
    "koa-multer": "^1.0.2",
    "koa2-cors": "^2.0.6",
    "md5": "^2.2.1",
    "mysql": "^2.18.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "babel-eslint": "10.1.0",
    "nodemon": "^2.0.3",
    "eslint": "6.8.0"
  }
}

app.js

const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const cors = require('koa2-cors');
const router = new Router()

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')

const config = require('./config')
/*
这里就设置一下就好,比如./routes/users里还有 /a和/b,我们只需要设置
const routes = require('./routes/users')直接就可以,不用像之前那样
const routesA = require('./routes/users/a');访问就是直接
http://localhost:8080/a
这里要特别注意哦
*/
const routes = require('./routes/users')
const indexs = require('./routes/index')

const port = process.env.PORT || config.port

// error handler
onerror(app)
app.use(cors());

// middlewares
app.use(bodyparser())
    .use(json())
    .use(logger())
    .use(require('koa-static')(__dirname + '/public'))
    .use(views(path.join(__dirname, '/views'), {
    options: {settings: {views: path.join(__dirname, 'views')}},
    map: {'njk': 'nunjucks'},
    extension: 'njk'
}))
/*这个就默认这样,不管你有多少个路由都别改了,就这个默认注册一次就好了,不需要多次,我就是在这个困扰了好久*/
    .use(router.routes())
    .use(router.allowedMethods())


// logger
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - $ms`)
})


/*但是这里记得要加上哦*/
routes(router)
indexs(router)

app.on('error', function(err, ctx) {
    console.log(err)
    logger.error('server error', err, ctx)
})

module.exports = app.listen(config.port, () => {
    console.log(`Listening on http://localhost:${config.port}`)
})
{{item.name}}