Search code examples
node.jskoa

nodejs(koa):Can't set headers after they are sent


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!


Solution

  • 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.