koa-router使用错误 TypeError: middleware must be a function!
const Koa = require('koa');
const router = require('koa-router');
const app = new Koa();
const main = ctx => {
ctx.response.body = 'This is homepage';
};
const about = ctx => {
ctx.response.type = 'html';
ctx.response.body = '<p>This is about page!</p>'
};
app.use(router.get('/', main));
app.use(router.get('/about', about));
app.listen(3000);
运行代码 报错如下:
if (typeof fn !== ‘function’) throw new TypeError(‘middleware must be a function!’);
TypeError: middleware must be a function!
解决:
const Koa = require('koa');
const router = require('koa-router')(); // 引入实例化路由 或者 const router = new Router();
const app = new Koa();
const main = ctx => {
ctx.response.body = 'This is homepage';
};
const about = ctx => {
ctx.response.type = 'html';
ctx.response.body = '<p>This is about page!</p>'
};
router.get('/', main);
router.get('/about', about)
app.use(router.routes()); // 启动路由
app.listen(3000);
结果: