Aero Wang
Aero Wang

Reputation: 9227

How to specify a static folder in Koa only when using a specific route?

I've noticed Koa's middleware such as koa-static (https://github.com/koajs/static) does not support serving a a static folder when using a specific route such as "dashboard", it seems to only support serving static folder globally...what might be the best solution to this challenge?

For example, I can try:

app.use(...)
   .use(async function(ctx){
      if ('/dashboard' === ctx.path) {
        let body = await static('./build');
        return body;
      }
   });

OR

app.use(...)
   .use(async function(ctx){
      if ('/dashboard' === ctx.path) {
        await static('./build');
      }
   });

the result is simply "Not Found".

Upvotes: 2

Views: 488

Answers (1)

James Wayne
James Wayne

Reputation: 1912

Use koa-mount:

npm i koa-mount

const mount = require('koa-mount');

...
.use(mount('/dashboard', static('./build')));

Upvotes: 1

Related Questions