nodejs(koa):发送后无法设置headers

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

我有一个程序想要映射 /a/b/c.js url => /a:b:c.js 文件;

koa version:2.3.0 koa static version: 4.0.1

最小复制

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);

假设当前目录有一个文件a:b:c.js, 当我在浏览器中访问 locahost:8888\a\b\c.js 时, 程序总是报错 UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): Error: Can't set headers after they are sent.

感谢您的帮助!

试试这个:

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);

看来要用一个常用的函数做中间件,还得return下一个函数

我发现要解决这个问题,我必须在某些路由上禁用某些中间件。在我的例子中,设置 cookie 的是 passport.js 中间件,我不希望通过 /proxy 路径的请求发生这种情况。这是我的解决方案:

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'
    )
  )