问题描述
我有一个程序想要映射/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.0koa static version: 4.0.1
koa version:2.3.0koa 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 errorUnhandledPromiseRejectionWarning: 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):发送后无法设置头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!