1

I have a program which want to map /a/b/c.js url => /a:b:c.js file;

koa version:2.3.0 koa static version: 4.0.1

minimal reproduction

const KOA = require('koa');
const koaStatic = require('koa-static');

staticApp = new KOA()
staticApp.use((ctx, next) => {
  let path = ctx.path.split('/');
  path = path.filter(segment => segment)
  ctx.path = `/${path.join(':')}`;
  next()
})
staticApp.use(koaStatic(__dirname))
staticApp.listen(8888);

Assume current directory have a file a:b:c.js, when I access to locahost:8888\a\b\c.js in browser, program always get error UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): Error: Can't set headers after they are sent.

thanks for you help!

kwoktung
  • 572
  • 1
  • 4
  • 12

2 Answers2

4

Try this:

const KOA = require('koa');
const koaStatic = require('koa-static');

staticApp = new KOA()
staticApp.use((ctx, next) => {
  let path = ctx.path.split('/');
  path = path.filter(segment => segment)
  ctx.path = `/${path.join(':')}`;
  return next();
});
staticApp.use(koaStatic(__dirname));
staticApp.listen(8888);

It seems that if you want to use a common function as middleware, you have to return the next function.

Yi Kai
  • 630
  • 6
  • 9
  • 1
    Do you know the reason why common function as middlerware have to return the next function? thk – kwoktung Jul 17 '17 at 09:30
  • @Qiu I think it's because you have to return a promise from your middleware to work with other middlewares. The next return a promise, as you return it, you return a promise. See this issue for more discussions https://github.com/koajs/koa/issues/997 – Yi Kai Jul 17 '17 at 09:40
0

I found that to resolve this problem I had to disable some middleware on some routes. In my case it was passport.js middleware that was setting cookies, which I wanted NOT to happen on requests through the /proxy path. This is my solution:

const blacklistRoute = (fn, p) => async (ctx, next) => {
  if (ctx.request.path.startsWith(p)) {
    return next()
  } else {
    return fn(ctx, next)
  }
}

const app = ...

app
  .use(
    blacklistRoute(
      koaSession(passportCookieConfig, app),
      '/proxy'
    )
  )
Zach Smith
  • 8,458
  • 13
  • 59
  • 133