我正在探索koajs,并认为我已经理解了生成器,但显然情况并非如此。
module.exports.request = function* request() {
'use strict';
try {
yield check;
yield send;
} catch (ValidationError) {
this.status = 400;
this.body = ValidationError.message;
}
};
function* check() {
expect(this.body.param).to.be.a('number');
}
function* send() {
this.body.token = '654afssd98sf';
}
这将导致错误Cannot read property 'status' of undefined,因此上下文不知何故丢失了。
下面的代码片段可以工作,但不是所需的行为,因为即使检查抛出错误,它也会发出响应。
module.exports.request = function *request(){
'use strict';
try{
yield checkTransaction;
} catch(ValidationError){
this.status = 400;
this.body = ValidationError.message;
}
yield sendTransaction;
};
如果你有关于如何架构koa应用程序的建议,我也很高兴,因为有很多例子,但没有一个真正涵盖了koa架构设计的最佳实践。
编辑:上下文:
var koa = require('koa');
var requestLogger = require('koa-logger');
var body = require('koa-body');
var route = require('koa-route');
var app = module.exports = koa();
var test = require('./controllers/test');
// Logger
if(app.env === 'development'){
app.use(requestLogger());
}
app.use(body());
app.use(function *setup(next){
this.type = 'application/json';
yield next;
});
app.use(route.post('/test', test.request));
app.use(route.put('/test', test.authenticate))
if (!module.parent) {
app.listen(3000);
console.log('listening on port 3000');
}发布于 2015-06-28 17:56:16
经过评论和思考,我确信你的错误是忘记将next添加到生成器函数中。
module.exports.request = function* request(next) {
'use strict';
try {
yield check;
yield send;
} catch (ValidationError) {
this.status = 400;
this.body = ValidationError.message;
}
};
function* check() {
expect(this.body.param).to.be.a('number');
}
function* send() {
this.body.token = '654afssd98sf';
}
https://stackoverflow.com/questions/30576845
复制相似问题