Node.js / Express.js-app.router如何工作?

node.js Node.js

TomJinJin

2020-03-19

在提出app.router疑问之前,我至少应该解释一下使用中间件时发生的事情。要使用中间件,要使用的功能是app.use()当执行中间件时,它将使用next()或使其调用下一个中间件,从而不再调用任何中间件。这意味着我放置中间件调用的顺序很重要,因为某些中间件依赖于其他中间件,而接近末尾的某些中间件甚至可能不会被调用。

今天,我正在开发应用程序,并在后台运行服务器。我想进行一些更改并刷新页面,然后立即查看更改。具体来说,我正在更改布局。我无法使它正常工作,所以我在Stack Overflow中搜索了答案,并找到了这个问题它说要确保它express.static()在下面require('stylus')但是,当我查看该OP的代码时,我发现他app.router在中间件调用的最后就接到了他的电话,我试图弄清楚为什么会这样。

当我制作Express.js应用程序(版本3.0.0rc4)时,我使用了命令,express app --sessions --css stylus并且在app.js文件中,app.routerexpress.static()require('stylus')调用上方都设置了代码如此看来,如果它已经以这种方式设置,那么它应该保持这种方式。

重新排列代码以便可以看到手写笔更改后,它看起来像这样:

app.configure(function(){
  //app.set() calls
  //app.use() calls
  //...
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(__dirname + '/public', {maxAge: 31557600000}));
});

app.get('/', routes.index);

app.get('/test', function(req, res){
  res.send('Test');
});

So I decided that the first step would be to find out why it is important to even have app.router in my code. So I commented it out, started my app and navigated to /. It displayed my index page just fine. Hmm, maybe it worked because I was exporting the routing from my routes file (routes.index). So next I navigated to /test and it displayed Test on the screen. Haha, OK, I have no idea what app.router does. Whether it is included in my code or not, my routing is fine. So I am definitely missing something.

So Here Is My Question:

有人可以解释一下app.router它的作用,重要性以及在中间件调用中的位置吗?如果得到有关的简短说明,那也很好express.static()据我所知,express.static()是我的信息的缓存,如果应用程序找不到请求的页面,它将检查缓存以查看其是否存在。

第2211篇《Node.js / Express.js-app.router如何工作?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android