如何使用 Express 框架
# Express
Express 是一个简洁、灵活的 nodejs 的 web 应用开发框架。
什么是框架?
所谓框架,就是将一些常用的操作封装在了里面,我们不用再重复书写,直接使用框架里面提供的功能即可。
express 的特点如下:
- 易上手
- 高性能
- 扩展性强:可以自由的拆分和安装模块
安装 express
npm i express
下面是一个使用 express 快速搭建服务器的示例:
// 使用 express 快速搭建一个服务器
const express = require('express');
const app = express();
app.get('/',(req,res)=>{
res.send('Hello,express');
}).listen(3000,()=>{
console.log('the server is running on port 3000...');
})
2
3
4
5
6
7
8
9
express 本身是一个极简的框架,本身是由一个路由和中间件组成的框架。
# 中间件
本来正常的过程是前端发送请求到后端,后端对这个请求进行处理,然后给前端返回响应。那么中间件的作用就是在接收到前端的请求后,作出一系列的工作。
中间件的语法:
function 中间件的名字(req,res,next){
// req 代表 http 请求
// res 代表 http 响应
// next 代表调用下一个中间件
}
2
3
4
5
也就是说,中间件会对http请求进行处理,处理完成之后,交给下一个中间件。
下面是一个中间件的简单示例:
const express = require('express');
const app = express();
function one(req,res,next){
console.log('正在执行 one 中间件');
next();
console.log('one 中间件执行完成');
}
function two(req,res,next){
console.log('正在执行 two 中间件');
next();
console.log('two 中间件执行完成');
}
function three(req,res,next){
console.log('正在执行 three 中间件');
next();
console.log('three 中间件执行完成');
}
// 注册中间件
app.use(one);
app.use(two);
app.use(three);
app.get('/',(req,res)=>{
res.send('<h1>Hello,express!!!</h1>')
}).listen(3000,()=>{
console.log('服务器已经跑起来了,监听的 3000 端口');
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
效果如下:
Jie-Xie:demo Jie$ node index
服务器已经跑起来了,监听的 3000 端口
正在执行 one 中间件
正在执行 two 中间件
正在执行 three 中间件
three 中间件执行完成
two 中间件执行完成
one 中间件执行完成
2
3
4
5
6
7
8
通过上面的示例,主要是想说明一件事情,中间件的前后顺序是很重要的。顺序不对,可能导致代码报错。
一般来讲,我们不需要自己来写中间件,直接使用第三方的中间件即可。
# 常见中间件
# body-parser
在nodejs原生http模块中,获取post请求数据的方式是基于流来进行操作的。需要不停的监听 data事件来接收数据,监听 end 事件来表示请求体里面的数据已经接收完毕。
在 express 中,可以通过 body-parser 来接收post 的数据
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// 注册
// 解析 application/x-www-from-urlencodeed 数据
app.use(bodyParser.urlencoded({extended:false}));
// 解析 application/json 数据
app.use(bodyParser.json());
let str = `
<form method="POST" action="">
<div>
name : <input type="text" name="username">
</div>
<div>
age : <input type="text" name="userage">
</div>
<button>send</button>
</form>
`
app.use('/',(req,res)=>{
if(req.body.username && req.body.userage){
console.log(req.body);
res.send(`name为${req.body.username},age 为 ${req.body.userage}`)
} else {
res.send(str);
}
}).listen(3000,()=>{
console.log('服务器已经跑起来了,监听的 3000 端口');
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 路由
所谓路由,就是对请求进行合适的导航。
在 express 中,通过 app.use 方法就可以配置路由。使用 app.use 配置的路由,不需要关心请求类型,无论是get,还是post,还是put...都OK,只要路径配上就OK了。
app.get、app.post ....就是 app.use 的别名。
后面我们在配置路由的时候,更多的还是使用app.get、app.post 这种方式,这样代码更加清晰一些。
快速入门示例如下:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// 注册
// 解析 application/x-www-from-urlencodeed 数据
app.use(bodyParser.urlencoded({extended:false}));
// 解析 application/json 数据
app.use(bodyParser.json());
app.get('/',(req,res)=>{
res.send('这是首页');
})
app.get('/login',(req,res)=>{
res.send('这是登陆页面');
})
app.get('/register',(req,res)=>{
res.send('这是注册页面');
})
app.listen(3000,()=>{
console.log('服务器已经跑起来了,监听的 3000 端口');
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
从 express 4.0 开始,路由成为了一个单独的中间件。
在后面的开发中,我们直接使用 express所提供的路由中间件,路由的配置单独书写一个文件。
示例如下:
// index.js
const express = require('express');
const app = express();
const router = require('./router');
app.use('/',router);
app.listen(3000,()=>{
console.log('服务器已经跑起来了,监听的 3000 端口');
});
// router.js
// 这个就是路由配置文件
const express = require('express');
const router = express.Router();
// 之后所有的配置就都在 router 上面
router.get('/',(req,res)=>{
res.send('这是首页');
})
router.get('/login',(req,res)=>{
res.send('这是登陆页');
})
router.get('/contact',(req,res)=>{
res.send('这是联系我们');
})
module.exports = router; // 导出这个路由配置
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 静态资源
什么是静态资源?
所谓静态资源,就是指图片、html 文件、css 文件、字体、图标都是静态资源。
在express,内置了一个处理静态资源的中间件。语法如下:
app.use(express.static(静态资源目录))
__dirname:当前所在目录
__filename: 当前文件
2
具体代码示例如下:
const express = require('express');
const app = express();
// 设置我的静态资源目录
app.use(express.static(__dirname + '/public'));
app.listen(3000,()=>{
console.log('服务器已经跑起来了,监听的 3000 端口');
});
2
3
4
5
6
7
8
9
# express 脚手架
什么是脚手架。使用脚手架可以帮助我们快速的搭建一个项目的目录。
要使用express脚手架,首先第一步需要全局安装,命令如下:
npm i express-generator -g
之后就可以使用express命令来创建项目:
express maoyan
但是这个时候是没有依赖的,需要 npm i 来安装依赖,然后就可以运行了。
使用 npm start 来启动项目。
# 脚手架搭建的项目目录
- app.js:核心服务器文件,中间件的使用就是在这个文件中
- bin:里面存在一个WWW文件,会引入 app.js,做一些原生node的设置
- node_modules:依赖包
- package-lock.json:锁定依赖的版本
- package.json:各种依赖的配置
- public:静态目录
- routes:配置路由
- views:设置模板(使用模板引擎的时候会用到)