koa初学的example运行抛出异常?
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 回复
中间件必须是个generator,就是带星号的函数,而且你代码中用的ctx这是koa2的写法,但你装的好像是koa1? 总之提供两种写法供你参考一下吧
koa1
app.use(funciton*(next){
console.log("step1")
yield next
console.log("step3")
this.body = "hello"
})
app.use(function*(next){
console.log("step2");
})
koa2
app.use(async function(ctx,next){
console.log("step1")
await next()
console.log("step3")
ctx.body = "hello"
})
app.use(async function(next){
console.log("step2");
})
koa2需要用babel转换成es5代码才能运行
@yakczh 中间件只接收三个参数:err,ctx,next,参数都在ctx里,你说的打印格式这种不就可以通过url传参控制么?
贴一段我的代码吧,献丑了
/**
* Created by admin on 16/4/2.
*/
"use strict"
//环境变量初始化,默认development环境
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
require('source-map-support').install();
require("babel-polyfill");
var koa = require('koa');
var morgan = require('koa-morgan');
var configs = require('../configs');
var redis = require('./components/redis');
var mysql = require('./components/mysql');
var ipnet = require('xz-ipnet')();
const app = new koa();
//自定义错误处理
app.use(async (ctx, next) => {
try {
await next()
if (ctx.status === 404) ctx.throw(404)
} catch (err) {
ctx.status = err.status || 500
ctx.body = err.body || err.message
console.error(ctx.url);
console.error(err.toString());
console.error(err.stack+"\n");
}
})
//访问日志,apache格式
var logformat = {
production : ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" - [:response-time ms]',
dev : 'dev'
}
app.use(morgan(app.env == 'production'?logformat.production:logformat.dev));
//redis连接
app.use(redis(configs.redis));
//mysql连接池
app.use(mysql(configs.database));
//ip查询服务
app.use(async function(ctx,next) {
ctx.ipnet = ipnet;
await next();
});
app.use(require('./routes').routes());
app.on('error',(err,ctx) => {
console.error(ctx.url);
console.error(err);
console.error(err.stack);
});
app.proxy = true;
app.listen(3000);