koa初学的example运行抛出异常?
发布于 10 年前 作者 Web-Kevin 15603 次预览 最后一次回复是 9 年前 来自 问答
lz最近刚接触nodejs,
使用koa写了这个 https://github.com/koajs/koa#example 例子
const Koa = require('koa');
const app = new Koa();
// logger
app.use((ctx, next) => {
const start = new Date;
return next().then(() => {
const ms = new Date - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
但每次运行都是有
assert.js:89
throw new assert.AssertionError({
^
AssertionError: app.use() requires a generator function
网上搜到了 https://github.com/alexmingoia/koa-router/issues/177 可是还是抛出同样异常
所以来请教各位大神
还有没有express经验直接学koa学习曲线怎么样?
7 回复
我也刚开始学,感觉是你的koa版本有点旧,还不支持非generator function 自豪地采用 CNodeJS ionic
@lian774739140 我之前也怀疑,查了是1.1.2,最新的是2.0.0-alpha.3 我去下个试试 多谢
升级了koa2 提示 constructor() { ^ TypeError: Class constructors cannot be invoked without ‘new’
中间件必须是个generator,就是带星号的函数,而且你代码中用的ctx这是koa2的写法,但你装的好像是koa1? 总之提供两种写法供你参考一下吧
koa1
koa2
koa2需要用babel转换成es5代码才能运行
使用这个吧https://github.com/17koa/koa-generator
@zstxt1989 中间件里需要要传入额外的参数呢,比如打印日志appender 或者打印格式 打印详细/简要等级 这些参数从哪里传进去呢?
@yakczh 中间件只接收三个参数:err,ctx,next,参数都在ctx里,你说的打印格式这种不就可以通过url传参控制么?
贴一段我的代码吧,献丑了