express

一、安装Node.js

进入Node.js官网下载并安装,选exe,添加环境变量

在使用npm命令时,如果直接从国外的仓库下载依赖,有时候下载速度很慢,甚至会下载不下来。这时我们可以更换npm的仓库源,提高下载速度。

查看npm源地址:

1
npm config get registry

更换npm源为淘宝镜像:

1
npm config set registry https://registry.npm.taobao.org/

如果设置了npm为淘宝镜像,需要恢复为默认源时:

1
npm config set registry https://registry.npmjs.org/

设置好之后,记得通过 npm config get registry 查看源是否设置成功。

注意:如果只是想临时更换源地址,可以进行如下操作:

1
npm install packagname -g --registry=https://registry.npm.taobao.org

国内npm源地址

1
2
3
4
5
6
7
8
npm 官方原始镜像:https://registry.npmjs.org/
淘宝 NPM 镜像:https://registry.npm.taobao.org
阿里云 NPM 镜像:https://npm.aliyun.com
腾讯云 NPM 镜像:https://mirrors.cloud.tencent.com/npm/
华为云 NPM 镜像:https://mirrors.huaweicloud.com/repository/npm/
网易 NPM 镜像:https://mirrors.163.com/npm/
中科院大学开源镜像站:http://mirrors.ustc.edu.cn/
清华大学开源镜像站:https://mirrors.tuna.tsinghua.edu.cn/

二、安装express和express-generator

1
2
npm install -g express
npm install -g express-generator

三、生成项目

在项目名称的后面添加 -e 那么创建出来的模板文件就是.ejs类型,语法是与html相同

1
express APP_NAME -e

四、使用框架

index.ejs内容修改,跳转html

1
2
3
4
5
6
7
8
<!DOCTYPE html>
<html>
<body>
<script>
window.location.replace("index.html");
</script>
</body>
</html>

模板web网页全部放入public文件夹下

其他

将ejs文件改为html

若希望模板文件的后缀为.html(通常只是为了看着更舒服),那么在手动将.ejs换成.html后,还需要对app.js文件进行设置

1
2
3
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
1
2
3
4
5

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html'); //app.set('view engine', 'ejs');

渲染

将需要渲染的文件放入views文件,静态文件放入public文件夹
放入views的文件,需要在index.js中添加路由,类似

1
2
3
4
5
6
7
8
9
10
11
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express /' });
});

router.get('/index.html', function(req, res, next) {
res.render('index', { title: 'Express index' });
});
router.get('/services.html', function(req, res, next) {
res.render('services', { title: 'Express2' });
});

显示所有图片示例

1
2
3
<% for(let i = 0 ; i<image.length ; i++){ %>
<img loading="lazy" src=<%= image[i] %> alt="Smiley face" width="200" height="200">
<% } %>
1
2
3
4
5
6
7
8
9
10
11
12
13
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {
title: 'Express',
display: "image",
image: function () {
var re = fs.readdirSync('public/images')
for (i = 0; i < re.length; i++)
re[i] = 'images/' + re[i];
return re;
}(),
});
});
-->

请我喝杯咖啡吧~

支付宝
微信