nodejs(koa):发送后无法设置头 [英] nodejs(koa):Can't set headers after they are sent

查看:177
本文介绍了nodejs(koa):发送后无法设置头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

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.

感谢您的帮助!

推荐答案

尝试一下:

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.

这篇关于nodejs(koa):发送后无法设置头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆