nodejs学习笔记 | Express

585 阅读5分钟

| 什么是express

基于nodejs平台而开发出来的web开发框架。
Express的作用与nodejs内置的http模块类似,是专门用来创建web服务器的。 本质是npm的第三方包,提供了快速创建web服务器的便捷方法。

| 能做什么?

  • 创建服务器
  • 提供api接口

| 使用

  1. 安装
npm i express

2.创建基本服务器

const express = require('express');
const app = express();
app(routes).listen(3000, () => {
    console.log('Server running at http://127.0.0.1:3000/');
});

3.监听get请求

app.get('/login', (req, res) => {
    res.send(req.query);
});

4.监听post请求

app.post'/postData', (req, res) => {
    res.send(req.query);
});

5.响应内容res.send

app.post'/postData', (req, res) => {
    res.send('响应内容');
});

6.获取url携带的查询参数

app.get('/login', (req, res) => {
    // res.query 默认是{}
    // 通过链接添加?age=20&name=zs发送请求
    res.send(req.query); // {age:20, name:zs}
});

7.获取url中的动态参数

app.get('/delete/:name/:id', (req, res) => {
    let { id, name } = req.params;
    res.send(`删除id为${id}${name}成功!`);
});

8.静态资源处理express.static()
exprss提供了一个函数express.static(),可以用来创建一个静态资源服务器 例如,开放public目录下的文件

app.use(express.static('public'))

访问文件
http://localhost:3000/images/bg.jpg

注意:

  • 这样指定的public不会出现在url上
  • 如果需要指定public在路径上出现需要挂载路径前缀
    写法:
app.use('/public', express.static('public'))

访问文件
http://localhost:3000/public/images/bg.jpg

托管多个静态资源目录

app.use(express.static('public'))
app.use(express.static('public2'))

访问时,会按目录添加顺序来查找所需文件

| Express 路由

广义上,路由就是映射关系,在Express中路由是指客户端请求服务器处理函数之间的映射关系。
Express的路由组成

  • 请求类型,如post,get
  • 请求的url地址
  • 处理函数
// 格式
app.METHOD(PATH, CALLBACK)

// example
// get请求
app.get('/delete/:name/:id', (req, res) => {
    let { id, name } = req.params;
    res.send(`删除id为${id}${name}成功!`);
});

// post请求
app.post('/delete/:name/:id', (req, res) => {
    let { id, name } = req.params;
    res.send(`删除id为${id}${name}成功!`);
});

路由匹配过程

  1. 每个请求到达服务器之后,先结果路由匹配,匹配成功才调用对应处理函数
  2. 匹配按定义的顺序进行

image.png

1.使用
简单用法,直接挂载在app上(不推荐)

app.js

// 1.创建服务器
const express = require('express');
const app = express();

// 2.开启服务器
app.listen(3000, () => {
    console.log('Server running at http://127.0.0.1:3000/');
});

// 3. 监听客户端的GET和POST请求
app.get('/login', (req, res) => {
    res.send(req.query);
});

模块化用法,将路由抽离出来为单独模块(推荐)

route.js

// 1.创建服务器
const express = require('express');
const router = express.Router();

// 3. 监听客户端的GET和POST请求
router.get('/login', (req, res) => {
    res.send(req.query);
});

module.exports = router

app.js中注册路由

const userRouter = require('./router/route.js');
app.use(userRouter);

| 中间件

中间件特值业务流程的中间处理环节
比如现实中的污水处理环节:

image.png 中间的三个处理环节可以叫做中间件。

1.中间件调用流程
当一个请求到达服务器之后,可以连续调用多个中间件,从而对请求进行拦截处理。

image.png

多个中间件之间共享一份res和req,因此我们可以在上游的中间件中为res或req进行操作,供下游的路由或中间件使用。

2.中间件格式
中间件本质是一个函数,可以自定义

const 中间件 = (req, res, next) {
    // 你的处理逻辑
    next(); // 必须在结尾调用
}

next()的作用是实现多个中间件调用的关键,把流转关系告诉给下一个中间件或路由

image.png

3.全局中间件
客户端发送的任何请求都会触发中间件,通过app.use(中间件函数)可以定义一个或多个全局生效的中间件

const 中间件 = (req, res, next) {
    // 你的处理逻辑
    next(); // 必须在结尾调用
};
const 中间件2 = (req, res, next) {
    // 你的处理逻辑
    next(); // 必须在结尾调用
};

app.use(中间件);
app.use(中间件2);

4.局部中间件
不通过app.use(中间件函数)注册的中间件都是局部中间件

const 中间件1 = (req, res, next) {
    // 你的处理逻辑
    next(); // 必须在结尾调用
};
const 中间件2 = (req, res, next) {
    // 你的处理逻辑
    next(); // 必须在结尾调用
};

/* 定义单个中间件 */ 
app.get('/login'、,中间件1 , (req, res) => {
    res.send(req.query);
});

/* 定义多个中间件 */ 
app.get('/login', 中间件1, 中间件2, (req, res) => {
    res.send(req.query);
});
// or
app.get('/login', [中间件1, 中间件2], (req, res) => {
    res.send(req.query);
});

5.中间件注意事项

  • 中间件注册要在路由定义之前注册
  • 不要忘记调用next()函数
  • 中间件触发顺序时机 :请求=>中间件=>请求回调

6.中间件5大类

  1. 应用级别
  2. 路由级别
  3. 错误级别
  4. express内置中间件
  5. 第三方中间件

应用级别中间件
通过app.use()或app.get()绑定到app实例上的中间件就是应用级别的中间件

const 中间件1 = (req, res, next) {
    // 你的处理逻辑
    next(); // 必须在结尾调用
};

// 应用级别的中间件
app.get('/login', 中间件1 , (req, res) => {
    res.send(req.query);
});
app.use(中间件1);

路由级别中间件
绑定到express.Router()实例上的中间件

const 中间件1 = (req, res, next) {
    // 你的处理逻辑
    next(); // 必须在结尾调用
};

// 路由级别的中间件
router.use(中间件1);

错误级别中间件
错误级别中间件的作用:专门捕获整个项目发生的异常错误,赋值项目异常而崩溃。
格式:处理函数必须要有4个参数`(err, req, res, next)

const 错误中间件 =(err, req, res, next) {
    console.log('发生了错误',err);
    res.send(err.message) 
};

// 路由级别的中间件
app.use(错误中间件);

注意:

  • 必须注册在所有路由之后
  • next可不用执行

内置中间件
Express内置了3个常用的中间件,极大提高了Express项目的开发效率和体验:

  1. express.static 托管静态资源
  2. express.json 解析JSON格式请求体数据
  3. express.urlencoded 解析URL-encoded格式请求体
app.use(express.json())

第三方中间件
非Express官方内置的,由第三方开发的中间件,需要下载,如body-parser
官方内置的express.urlencoded其实是基于body-parser开发出来的

| 热更新代码插件nodemon

nodejs代码频繁修改需要重启服务器,非常繁琐,此时需要安装nodemon来自动帮助重启项目

1.安装

npm i -g nodemon

2.使用

nodemon app.js