koa-router错误 TypeError: middleware must be a function!

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 = '

This is about page!

' }; app.use(router.get('/', main)); app.use(router.get('/about', about)); app.listen(3000);

运行代码 报错如下:
koa-router错误 TypeError: middleware must be a function!_第1张图片
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 = '

This is about page!

' }; router.get('/', main); router.get('/about', about) app.use(router.routes()); // 启动路由 app.listen(3000);

结果:
koa-router错误 TypeError: middleware must be a function!_第2张图片
koa-router错误 TypeError: middleware must be a function!_第3张图片

你可能感兴趣的:(koa)