我创建了一个网页,在本地使用它来保存有关随机主题和大学内容的信息。我有很多如下所示的路线:
//app.js - using node and express
app.get('/page1', function(req, res){
res.render('page1');
});
app.get('/page2', function(req, res){
res.sendFile('views/page2.html', { root: __dirname });
});
这些路由中的每一个都有一个 .ejs
文件或 .html
文件,而且它们都非常小。
我不认为我犯了任何重大错误,但我有一种感觉,我没有使用“最佳实践”,或者至少可以做一些不同的事情。
- 大量使用这样的路线有什么问题吗?是否应该更改某些内容来优化页面的呈现?
- 正如我之前所说,我在大多数页面上使用
.ejs
,并且大多数页面都具有相同的header.ejs
和footer。 ejs
。每次我更改具有相同页眉/页脚的页面时,它们是否会再次加载,或者由于它们使用相同的页眉/页脚文件,服务器仅请求其间的内容? - 使用 res.render 和 res.send 有什么区别?
- 我应该使用不同的语法:
const express = require('express');
&const app = express();
而不是varexpress = require('express');
&var app = express();
```或者这个
app.get('/page1', (req, res) => {
res.render('page1');
});
```
而不是上面的第一 block 代码。
谢谢! :D
最佳答案
Is there anything wrong with using a lot a routes like this? Should change something to optimize the rendering of my pages?
技术上没有任何问题。许多普通的 res.sendFile()
路由可能可以用单个 express.static()
中间件语句替换,以简化代码。
许多不将任何自定义数据传递给 EJS 的 res.render()
路由也可能被单个中间件替换,该中间件处理模板文件的整个目录(及其相应的路线)或文件列表。那会更多DRY而不是单独拼出每条路线。
As I said before, I'm using .ejs on most of the pages, and most of them have the same header.ejs and footer.ejs. Every time I change pages that have the same header/footer, do they get loaded again, or since they are using the same header/footer files the server only requests the content in between?
EJS 将模板缓存在内存中(除非您禁用缓存),因此页眉和页脚模板不会从磁盘反复加载。
what's the difference between using res.render and res.send?
文档中全面介绍了这些内容。简而言之,res.render()
支持您的模板引擎和本地数据以提供给模板引擎,以允许其向模板添加数据。 res.send()
只是发送您提供的原始内容。
Should I be using a different syntax: const express = require('express'); & const app = express(); instead of var express = require('express'); & var app = express();
每当您声明的变量应该获得其初始值并且不再被分配时,使用 const 被认为是一个好习惯。除了一些编码安全性之外,这有时还可以允许解释器在使用变量时进行更多优化(因为它的值无法更改)。
关于javascript - 在node.js中设置很多路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53218991/