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

2019-08-17 16:28发布

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!

标签: node.js koa
1条回答
小情绪 Triste *
2楼-- · 2019-08-17 17:31

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.

查看更多
登录 后发表回答