Node.js Express – app.all(“*”,func)在访问根域时不会被调用

我试图设置一个全局函数,每个页面加载都被调用,而不pipe它在我的网站的位置。 根据Express的API,我已经使用了

app.all("*", doSomething); 

每个页面加载调用函数doSomething,但它不完全工作。 除了基本域的页面加载(例如http://domain.com/pageA将调用该函数,但http://domain.com不会),该函数会触发每个页面加载。 有谁知道我在做什么错?

谢谢!

我知道这是一个老的,但对某个人来说也许是有用的。

我认为这个问题可能是:

 app.use(express.static(path.join(__dirname, 'public'))); var router = express.Router(); router.use(function (req, res, next) { console.log("middleware"); next(); }); router.get('/', function(req, res) { console.log('root'); }); router.get('/anything', function(req, res) { console.log('any other path'); }); 

在任何path上调用的中间件在哪里,但是/

这是因为express.static默认为public/index.html开启/

为了解决这个问题,给静态中间件添加参数:

 app.use(express.static(path.join(__dirname, 'public'), { index: false })); 

我敢打赌,你放置

 app.get('/', fn) 

以上

 app.all("*", doSomething); 

请记住,Express将按照它们注册的顺序执行中间件function,直到发送响应为止

如果你想在每个请求上运行一些代码,你不需要使用路由器。

只需在路由器上方放置一个中间件,它就会在每个请求中被调用:

 app.use(function(req, res, next){ //whatever you put here will be executed //on each request next(); // BE SURE TO CALL next() !! }); 

希望这可以帮助

链中的app.all('*')在哪里? 如果毕竟其他路线,它可能不会被调用。

 app.post("/something",function(req,res,next){ ...dothings.... res.send(200); }); app.all('*',function(req,res) { ...this NEVER gets called. No next and res already sent }); 

除非你打算把它作为最后一个,在这种情况下,你必须确保在前面的路由中调用next()。 例如:

 app.post("/something",function(req,res,next){ ...dothings.... next();}); app.all('*',function(req,res) { ...this gets called }); 

另外,什么在做什么? 你确定没接到电话吗?

我也有这个问题,我发现你的doSomething函数有多less参数可能是一个因素。

 function doSomething(req, res, next) { console.log('this will work'); } 

然而:

 function doSomething(req, res, next, myOwnArgument) { console.log('this will never work'); }