我用Koa构建了一个小型测试服务器。它应该为生活在同一个目录(和子目录)中的所有文件提供服务,但是需要使用基本的auth进行身份验证。因此,我使用的包是koa-静态 & koa-基本数据
我不知道如何把两种中间件结合起来?当使用: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);发布于 2015-10-30 11:25:01
yield 必须有才能对中间件进行包装:
app.use(function *() {
yield serve('.')
});或直接使用没有包装器功能的中间件:
app.use(serve('.'));https://stackoverflow.com/questions/33433785
复制相似问题