我使用Koa构建了一个小型测试服务器。它应该服务于生活在同一目录(和子目录)中的所有文件,但需要使用基本身份验证进行身份验证。因此,我正在使用套餐koa-static& koa-basic auth
我无法弄清楚如何组合两个中间件?
使用时:app.use(function *() { });
预计会this.body = 'text'
而不是koa-static
。
这是完整的代码:
"use strict";
var koa = require('koa')
, serve = require('koa-static')
, auth = require('koa-basic-auth');
var app = koa();
// Default configuration
let port = 3000;
app.use(function *(next){
try {
yield next;
} catch (err) {
if (401 == err.status) {
this.status = 401;
this.set('WWW-Authenticate', 'Basic');
this.body = 'Access denied';
} else {
throw err;
}
}
});
// Require auth
app.use(auth({ name: 'admin' , pass: 'admin'}))
//Serve static files
//DOESN'T WORK
app.use(function *() {
serve('.')
});
// WORKS
app.use(function *(){
this.body = 'secret';
});
app.listen(port);
答案 0 :(得分:2)
您必须yield
才能制作中间件的包装:
app.use(function *() {
yield serve('.')
});
或直接使用没有包装函数的中间件:
app.use(serve('.'));