6

我有一个非常简单的服务器可以玩:

import * as http from 'http';
import * as Koa from "koa";
import { Request, Response, Context } from "koa";
import * as Router from "koa-router";
import * as bodyParser from "koa-bodyparser";

const HTTPPORT = 3000;

var app:Koa = new Koa();
var router:Router = new Router();

app.use(async (ctx:Context, next)=> {
  console.log(ctx);
  return await next();
});

router.get('/', function (ctx) {
  ctx.body = "hello world";
  console.log("success")
});

app
  .use(bodyParser)
  .use(router.routes())
  .use(router.allowedMethods());

const  httpServer = http.createServer(app.callback());
//listen on provided port
httpServer.listen(HTTPPORT, () => {
  console.log(`${httpServer.address().address} (${httpServer.address().family}) is listening on port ${httpServer.address().port}`)
});

不幸的是,它TypeError: ctx.onerror is not a function一直在抛出。

按照 GitHub 上的 koa-router 示例(https://github.com/alexmingoia/koa-router),我的代码应该可以正常工作......你能帮我解决这个 onError 消息有什么问题吗?

启动服务器记录以下内容:

:: (IPv6) is listening on port 3000
{ request:
   { method: 'GET',
     url: '/',
     header:
      { host: 'localhost:3000',
        connection: 'keep-alive',
        'cache-control': 'max-age=0',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        'upgrade-insecure-requests': '1',
        accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        dnt: '1',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'en-US,en;q=0.9' } },
  response: { status: 404, message: 'Not Found', header: {} },
  app: { subdomainOffset: 2, proxy: false, env: 'development' },
  originalUrl: '/',
  req: '<original node req>',
  res: '<original node res>',
  socket: '<original node socket>' }
/.../node_modules/koa/lib/application.js:147
    const onerror = err => ctx.onerror(err);
                               ^

TypeError: ctx.onerror is not a function
    at Array.onerror (/.../node_modules/koa/lib/application.js:147:32)
    at listener (/.../node_modules/on-finished/index.js:169:15)
    at onFinish (/.../node_modules/on-finished/index.js:100:5)
    at callback (/.../node_modules/ee-first/index.js:55:10)
    at ServerResponse.onevent (/...s/node_modules/ee-first/index.js:93:5)
    at emitNone (events.js:111:20)
    at ServerResponse.emit (events.js:208:7)
    at onFinish (_http_outgoing.js:723:10)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

注意找到解决方案后,我将工作代码上传到 gethub 供所有感兴趣的人使用,请在此处找到:https ://github.com/wzr1337/node.koa.webpack.starter

4

1 回答 1

9

真可惜……这是bodyParser对。bodyParser()

所以

app
  .use(bodyParser())
  .use(router.routes())
  .use(router.allowedMethods());

工作得很好..

感谢@saadq 的提示.. 我是盲目地看到我错过了()......

于 2018-01-11T09:34:32.327 回答