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!

2 Answers 2

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.

2
  • 1
    Do you know the reason why common function as middlerware have to return the next function? thk
    – kwoktung
    Jul 17, 2017 at 9: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 github.com/koajs/koa/issues/997
    – Yi Kai
    Jul 17, 2017 at 9: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'
    )
  )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.