Node-----express

143 阅读7分钟

初识express

安装express:

npm i express

基本使用

创建基本的web服务器:

// 1.导入express
const express = require("express");

// 2.创建web服务器
const app = express();

// 3.调用app.listen(端口号,启动后的回调函数),开启服务器
app.listen(80, () => {
  console.log("80端口开启成功,地址为http://127.0.0.1");
});

监听GET和POST请求以及响应服务端

app.get(url, (req, res) => {})

app.post(url, (req, res) => {})

// 1.导入express
const express = require("express");

// 2.创建web服务器
const app = express();

// 4.监听GET和POST请求,并向客户端响应具体的内容
app.get("/user", (req, res) => {
  res.send({ id: 1, name: "zs", age: 20 });
});

app.post("/user", (req, res) => {
  res.send("post请求成功");
});
// 3.调用app.listen(端口号,启动后的回调函数),开启服务器
app.listen(80, () => {
  console.log("80端口开启成功,地址为http://127.0.0.1");
});

image.png

image.png

获取URL中携带的参数

req.query

app.get("/", (req, res) => {
  // req.query默认是一个对象
  // 客户端使用 ?name=zs&age=20 这种查询字符串形式,发送到服务器的参数
  // 可以通过 req.query 对象访问到,例如:
  // req.query.name,req.query.age
  
  console.log(req.query);
  
  res.send(req.query);
});

image.png

image.png

获取URL中的动态参数

req.params

例如:/user/detail/:id,后面的:id就是动态参数,可以动态的更改

app.get("/user/:id", (req, res) => {
  // req.params是动态匹配到的URL参数;

  console.log(req.params);

  res.send(req.params);
});

image.png

注意点:

  • :后面的id参数可以更改

  • 动态参数可以不止一个

app.get("/user/:ids/:age", (req, res) => {
  // req.params是动态匹配到的URL参数;

  console.log(req.params);

  res.send(req.params);
});

image.png

express路由

在express中,路由就是客户端的请求与服务器处理函数之间的映射关系

express中的路由分为3个部分组成,分别是请求的类型,请求的URL地址,处理函数,格式如下:

app.METHOD(PATH,HANDLER)

// METHOD:请求的类型,例如:get,post
// PATH:请求的URL地址
// HANDLER:处理函数

基本使用

//匹配 GET 请求,且请求 URL 为 /
app.get("/", (req, res) => {
  res.send("GET请求");
});

//匹配 POST 请求,且请求 URL 为 /
app.post("/", (req, res) => {
  res.send("POST请求");
});

模块化路由

主文件:

const express = require("express");
const app = express();
// 1.导入路由模块
const router = require("./router");

// 2.注册路由模块
app.use(router);

app.listen(80, () => {
  console.log("http://127.0.0.1");
});


模块路由 router.js:

// 1.导入express对象
const express = require("express");

// 2.创建路由对象
const router = express.Router();

// 3.挂载路由
router.get("/user/list", (req, res) => {
  res.send("获取user列表");
});
router.post("/user/add", (req, res) => {
  res.send("添加user");
});

// 4.向外导出路由对象
module.exports = router;

image.png

image.png

添加前缀:

// 1.导入路由模块
const router = require("./router");

// 2.注册路由模块
app.use("/api", router);

image.png

中间件

app.get("/", (req, res, next) => {
  next();
});

next函数的作用:用来实现多个中间件连续调用的关键,它表示把流转关系转交给下一个中间件或者路由

定义中间件

// 定义简单的一个中间件
const mw = (req, res, next) => {

  console.log(这是最简单的一个中间件);
  
  // 在当前中间件业务处理完毕之后,必须调用next()函数
  // 将流转关系转交给下一个中间件或者路由
  
  next();
};

全局生效的中间件

// 定义简单的一个中间件
const mw = (req, res, next) => {
  console.log(这是最简单的一个中间件);
  next();
};

//全局生效的中间件
app.use(mw);
  • 简化形式
app.use((req, res, next) => {
  console.log(这是最简单的一个中间件);
  next();
});

定义多个全局中间件

app.use((req, res, next) => {
  console.log("这是第一个中间件");
  next();
});
app.use((req, res, next) => {
  console.log("这是第二个中间件");
  next();
});
app.get("/user", (req, res) => {
  res.send("user page ");
});

image.png

定义局部生效的中间件

//定义一个中间件
const mw = (req, res, next) => {
  console.log("这是局部中间件");
  next();
};

//只在该路由中使用
app.get("/user", mw, (req, res) => {
  res.send("get user page ");
});

app.post("/user", (req, res) => {
  res.send("post user page ");
});

定义多个局部生效的中间件

const mw1 = (req, res, next) => {
  console.log("这是局部中间件1");
  next();
};
const mw2 = (req, res, next) => {
  console.log("这是局部中间件2");
  next();
};
const mw3 = (req, res, next) => {
  console.log("这是局部中间件3");
  next();
};

app.get("/user", mw1, mw2, mw3, (req, res) => {
  res.send("get user page ");
});
//或者
app.get("/user", [mw1, mw2, mw3], (req, res) => {
  res.send("get user page ");
});

中间件的分类

应用级别的中间件

通过 app.use()app.get()app.post() ,绑定到 app 实例上的中间件,叫做应用级别的中间件,代码示例如下:

// 应用级别的中间件(全局中间件)
app.use((req, res, next) => {
  next();
});

// 应用级别的中间件(局部中间件)
app.get("/", mw1, (req, res) => {
  res.send("Home Page");
});

路由级别的中间件

绑定到 express.Router() 实例上的中间件,叫做路由级别的中间件。它的用法和应用级别中间件没有任何区别。只不过,应用级别中间件是绑定到 app 实例上,路由级别中间件绑定到 router 实例上,代码示例如下:

const express = require("express");
const router = express.Router();

//路由级别的中间件
router.use("/user", (req, res, next) => {
  res.send("post user page ");
  next();
});

app.use("/", router);

错误级别的中间件

错误级别中间件的作用:专门用来捕获整个项目中发生的异常错误,从而防止项目异常崩溃的问题。

格式: 错误级别中间件的 function 处理函数中,必须有 4 个形参,形参顺序从前到后,分别是 (err, req, res, next)

注意: 错误级别的 中间件, 必须注册在所有路由之后!

// 错误级别的中间件
app.use((err, req, res, next) => {
  console.log("发生了错误" + err.message);
});

Express 内置的中间件

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

  • express.static 快速托管静态资源的内置中间件,例如: HTML 文件、图片、CSS 样式等(无兼容性)

  • express.json 解析 JSON 格式的请求体数据(有兼容性,仅在 4.16.0+ 版本中可用)

  • express.urlencoded 解析 URL-encoded 格式的请求体数据(有兼容性,仅在 4.16.0+ 版本中可用)

// 配置解析 application/json 格式数据的内置中间件
app.use(express.json());

// 配置解析 application/x-www-form-urlcoded 格式数据的内置中间件
app.use(express.urlencoded({ extended: false }));

  • 使用 express.json()
// 配置解析数据的中间件(全局)
app.use(express.json());

app.post("/user", (req, res) => {
  //在服务器中,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
  // 但是如果没有配置解析表单数据的中间件,则 req.body 默认等于 undefined
  console.log(req.body);
  res.send("User Page");
});

image.png image.png

  • 使用 express.urlencoded()
// 配置解析数据的中间件(全局)
app.use(express.urlencoded({ extended: false }));

app.post("/book", (req, res) => {
  //在服务器中,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
  // 但是如果没有配置解析表单数据的中间件,则 req.body 默认等于 undefined
  console.log(req.body);
  res.send("User Page");
});

image.png

image.png

第三方的中间件

非 Express 官方内置的,而是由第三方开发出来的中间件,叫做第三方中间件。在项目中,大家可以按需下载并配置 第三方中间件,从而提高项目的开发效率。

例如:在 express@4.16.0 之前的版本中,经常使用 body-parser 这个第三方中间件,来解析请求体数据。使用步 骤如下:

  • 运行 npm install body-parser 安装中间件

  • 使用 require 导入中间件

  • 调用 app.use() 注册并使用中间件

// 1. 导入解析表单数据的中间件 body-parser
const parser = require('body-parser')
// 2. 使用 app.use() 注册中间件
app.use(parser.urlencoded({ extended: false }))
// app.use(express.urlencoded({ extended: false }))

app.post('/user', (req, res) => {
  // 如果没有配置任何解析表单数据的中间件,则 req.body 默认等于 undefined
  console.log(req.body)
  res.send('ok')
})

使用express写接口

1. 创建基本的服务器

const express = require("express");

const app = express();

app.listen(80, () => {
  console.log("http://127.0.0.1");
});

2. 创建 API 路由模块

router.js

const express = require("express");

const router = express.Router();

module.exports = router;


app.jsconst router = require("./9_router");

app.use("/api", router);

3. 编写 GET 接口

router.js// 在这里挂载对应的路由
router.get('/get', (req, res) => {
  // 通过 req.query 获取客户端通过查询字符串,发送到服务器的数据
  const query = req.query
  // 调用 res.send() 方法,向客户端响应处理的结果
  res.send({
    status: 0, // 0 表示处理成功,1 表示处理失败
    msg: 'GET 请求成功!', // 状态的描述
    data: query, // 需要响应给客户端的数据
  })
})

4. 编写POST接口

app.js:

//配置数据解析
app.use(express.json());
app.use(express.urlencoded({ extended: false }));



router.js:

// 定义 POST 接口
router.post('/post', (req, res) => {
  // 通过 req.body 获取请求体中包含的 url-encoded 格式的数据
  const body = req.body
  // 调用 res.send() 方法,向客户端响应结果
  res.send({
    status: 0,
    msg: 'POST 请求成功!',
    data: body,
  })
})

5. 使用cors解决跨域问题

corsexpress 的一个第三方中间件。通过安装和配置 cors 中间件,可以很方便地解决跨域问题。

使用步骤分为如下 3 步:

  • 运行 npm install cors 安装中间件

  • 使用 const cors = require('cors') 导入中间件

  • 在路由之前调用 app.use(cors()) 配置中间件

// 一定要在路由之前,配置 cors 这个中间件,从而解决接口跨域的问题
const cors = require("cors");
app.use(cors());