Hedge
Hedge

Reputation: 16748

Serving static files via koa and using basic auth

I've build a small test-server using Koa. It is supposed to serve all files living in the same directory (and sub-directories) but requiring to authenticate with basic auth. Therefore I'm using the packages koa-static & koa-basic auth

I couldn't figure out how to combine both middlewares? When using: app.use(function *() { }); a this.body = 'text' is expected instead of using koa-static.

This is the complete code:

"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);

Upvotes: 1

Views: 998

Answers (1)

damphat
damphat

Reputation: 18956

you must have yield to make a wrapper of a middleware:

app.use(function *() {
  yield serve('.')
});

or directly use the middleware without the wrapper function:

app.use(serve('.'));

Upvotes: 2

Related Questions