问题描述
我正在运行最新的Express(截至撰写时为4.1.1).它具有此中间件,用于提供静态文件.
I am running the latest express (4.1.1 as of writing). It has this middleware included to serve static files.
因此,包含此中间件的常用代码是:
So the usual code to include this middleware is:
app.use(express.static(path.join(__dirname, 'public')));
很好,一切正常.但是,如果我尝试在此之前加入中间件,例如:
And great that all works fine. But if I try to include a middleware before that, eg:
app.use(function(req,res,next){
next();
}, express.static(path.join(__dirname, 'public')));
静态服务中间件现在为我提供404.
The serve-static middleware now gives me 404s.
我不确定为什么会这样.我是否错误地实现了在静态中间件之前的中间件?
I am not sure why this is happening. Did I implement the middleware that goes before the static middleware incorrectly?
推荐答案
您会注意到, app.use
接受可选路径和一个函数,而不是多个函数.因此,您应该使用自己的 app.use
调用定义每个中间件,如下所示:
You will notice that app.use
accepts an optional path and a function, not multiple functions. Therefore, you should be defining each middleware with its own app.use
call, as seen below:
app.use(function(req,res,next){
next();
});
app.use(express.static(path.join(__dirname, 'public')));
这篇关于在express.static之前具有中间件功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!