11.Express 应用程序中的中间件配置部分及路由模块拆分

书诚小驿2025/01/11前端知识库NodeJSExpress

一、基础中间件

1、express.json()用于解析 JSON 格式的请求体

当客户端发送 JSON 格式的请求数据时,该中间件会将请求体中的 JSON 字符串解析为 JavaScript 对象,并将其存储在 req.body 属性中,方便后续处理。

app.use(express.json());

2、express.urlencoded({ extended: true })用于解析 URL 编码格式的请求体

该中间件会将请求体中的 URL 编码字符串解析为 JavaScript 对象,并存储在 req.body 属性中。extended: true 表示使用第三方库 qs 来解析 URL 编码字符串,可以处理更复杂的表单数据结构。

app.use(express.urlencoded());

3、 cors()允许跨域资源共享(CORS)。

当客户端从不同的域向服务器发送请求时,浏览器会执行跨域资源共享检查。cors() 中间件会自动设置响应头,允许跨域请求。如果没有这个中间件,可能会出现跨域请求被浏览器阻止的情况。

npm install cors
  • app.js
const express = require("express");
const app = express();
const cors = require("cors");
app.use(cors());

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

4、morgan('dev')用于记录 HTTP 请求的日志。

morgan 是一个常用的 HTTP 请求日志中间件,'dev' 是预定义的输出格式,会以彩色输出请求方法、URL、状态码和响应时间等信息,方便开发者调试和监控应用程序的运行情况。

npm install morgan
  • app.js
const express = require("express");
const app = express();
const moragn = require("morgan");
app.use(moragn("dev"));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

二、路由模块拆分

1、挂载路由模块

当请求的 URL 以 /api/v1 开头时,Express 会将请求转发给该路由模块进行处理。这样可以将路由逻辑封装在单独的模块中,使代码更加模块化和易于维护。

  • 新建router/login.js
const express = require("express");
const router = express.Router();
router.get("/login", (req, res, next) => {
  console.log(req.method);
  res.send("loginForm");
});
module.exports = router;
  • 新建router/user.js
const express = require("express");
const router = express.Router();
router.get("/user", (req, res, next) => {
  console.log(req.method);
  res.send("userInfo");
});
module.exports = router;
  • 新建router/index.js
const express = require("express");
const router = express.Router();
router.use("/login", require("./login"));
router.use("/user", require("./user"));
module.exports = router;
  • 引入路由模块在app.js
const express = require("express");
const app = express();
// api,v1版本
app.use("/api/v1", require("./router"));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

2、定义控制器方法

控制器方法将路由处理逻辑从路由定义中分离出来,使代码更加模块化。每个控制器方法只负责处理特定的请求类型和路径

  • 新建controller/useController.js
exports.getUser = async () => {
  console.log(req.method);
  res.send("/userInfo");
};
exports.deleteUser = async () => {
  console.log(req.method);
  res.send("/userInfo");
};
  • 修改router/user.js
const express = require("express");
const router = express.Router();
const useController = require("../controlleruseController");
router
  .get("/user", useController.getUser)
  .delete("/user", useController.deleteUser);
module.exports = router;
最后更新时间' 2025/1/22 16:22:54