当前位置: 首页 > news >正文

如何使用脚手架工具开始,快速搭建一个 Express 项目的基础架构

前言

将从如何使用脚手架工具开始,快速搭建一个 Express 项目的基础架构。接着,文章将详细讲解 Express 中间件的概念、分类以及如何有效地使用中间件来增强应用的功能和性能。最后,我们将讨论如何制定合理的接口规范,以确保 API 的一致性和可维护性。

一、下载express模版

  1. 根据创建的自定义bincli命令下载express模版代码
bincli create express-project

image.png

  1. 切换express-project项目,打开终端命令
cd express-project
npm install
  1. 查看package.json是否安装了nodemon,没有的话重安一下
npm i nodemon
  1. 运行项目
npm run dev

报错原因:运行Express 应用时遇到了一个 ReferenceError,具体来说是因为在 app.js 文件中使用了一个未定义的变量 router。

image.png

二、Express中间件与接口规范

1、启动项目

  • 修改app.js
const express = require("express");
const app = express();const PORT = process.env.PORT || 3000;function logs(req) {console.log(`${req.method},${req.url},${Date.now()}`);
}app.get("/", (req, res) => {logs(req);res.send("/home");
});
app.get("/register", (req, res) => {logs(req);res.send("register");
});
app.get("/login", (req, res) => {logs(req);res.send("/login");
});
app.listen(PORT, () => {console.log(`Server is running at http://localhost:${PORT}`);
});
  • 运行项目
npm run dev

image.png

  • 打开postman客服端,send发送请求查看

image.png

2、注册中间件函数。

app.use()是 Express 应用的一个方法,这里注册的中间件将应用于所有路由。其中(req, res, next) => { ... } 是一个箭头函数,它接受三个参数。

  • req:请求对象,包含了请求的所有信息,如请求方法、URL、请求头和请求体等。
  • res:响应对象,用于发送响应给客户端。
  • next:一个函数,调用它将请求传递给下一个中间件函数。如果不调用 next(),请求将停止处理。

修改app.js

const express = require("express");
const app = express();const PORT = process.env.PORT || 3000;
app.use((req, res, next) => {console.log(`${req.method},${req.url},${Date.now()}`);next();
});app.get("/", (req, res) => {res.send("/home");
});
app.get("/register", (req, res) => {res.send("register");
});
app.get("/login", (req, res) => {res.send("/login");
});
app.listen(PORT, () => {console.log(`Server is running at http://localhost:${PORT}`);
});

注意:在 Express 应用中,中间件的执行顺序非常重要,因为它决定了请求处理的流程。app.use() 方法用于注册中间件函数,这些函数会按照它们被注册的顺序依次执行。如果中间件没有正确放置,可能会导致请求不经过预期的中间件处理,从而影响应用的行为。

三、Express中间件分类

1、应用程序级别中间件

应用程序级别中间件是绑定到 Express 应用实例的中间件。它对所有路由和请求都有效。
使用场景:适用于全局的请求处理,如日志记录、身份验证等。

app.use(function (req, res, next) {// 执行中间件逻辑next();
});

2、路由级别中间件

路由级别中间件是绑定到特定路由的中间件。它只对特定路由的请求有效。
使用场景:适用于特定路由的请求处理,如特定路径的权限检查、数据预处理等

  • 修改app.js
app.get('/', function (req, res, next) {console.log(req.method);next();
}, function (req, res, next) {console.log('route')next();
});
  • 启动项目
npm run dev

image.png

  • 打开postman客户端,发送请求

image.png

image.png

3、错误处理中间件

错误处理中间件用于捕获和处理在中间件链中发生的错误。
使用场景:通常放在所有其他中间件之后,以便捕获所有未处理的错误。

app.use(function (err, req, res, next) {// 处理错误console.error(err.stack);res.status(500).send('服务器内部错误');
});

4、内置中间件

Express API 参考手册

Express 内置了一些中间件函数,用于处理常见的任务。

express.static:用于提供静态文件服务。
express.json():用于解析 JSON 格式的请求体。
express.urlencoded():用于解析 URL 编码格式的请求体。

  1. express.Router() 用于创建模块化的路由处理器
  • 修改 router/index.js
const express = require('express')
const router = express.Router()
router.get('/', (req, res, next) => {console.log(req.method);res.send('/home')
})router.get('/user', (req, res, next) => {console.log(req.method);res.send('/users')
})
module.exports = router
  • 修改app.js
const express = require("express");
const router = require('./router/index.js');
const app = express();
app.use(router);const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {console.log(`Server is running at http://localhost:${PORT}`);
});
  • 运行项目
npm run dev
  • 打开客户端postman

image.png

  1. 添加路由的路径前缀。
  • app.js
const express = require("express");
const router = require('./router/index.js');
const app = express();
// 任何以 'node' 开头的请求路径都会被这个路由处理器处理。
app.use('node', router);const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {console.log(`Server is running at http://localhost:${PORT}`);
});
  • 运行项目
npm run dev
  • 打开客户端postman

未添加node前缀显示请求错误

image.png

添加node前缀后

image.png

  1. 404 错误处理中间件,当请求的路径没有匹配到任何定义的路由时,这个中间件会被调用,通常放在所有路由定义之后,确保它是最后一个中间件。
app.use((req, res, next) => {res.status(404).send('404 Not Found')
});
  1. 500 错误处理中间件,用于捕获和处理在应用中发生的错误,在所有其他中间件之后。
app.use((err, req, res, next) => {console.log(err);res.status(500).send('Service Error')
});

5、第三方中间件

第三方中间件是由社区开发的中间件,提供了各种功能扩展。

const cors = require('cors');
const morgan = require('morgan');
app.use(cors());
app.use(morgan('combined'));
http://www.lryc.cn/news/516371.html

相关文章:

  • 防止密码爆破debian系统
  • 高阶知识库搭建实战六、(向量数据库Faiss安装)(练习推荐)
  • 微信小程序获取图片使用session(上篇)
  • 代码随想录算法训练营第七十天 | 拓扑排序精讲,Dijkstra(朴素版)精讲,Dijkstra(堆优化版)精讲
  • 【保姆级爬虫】微博关键词搜索并获取博文和评论内容(python+selenium+chorme)
  • Excel 打印时-预览界面内容显示不全
  • nginx-限流(请求/并发量)
  • Vue——使用html2pdf插件,下载pdf文档到本地
  • 每日一题:BM1 反转链表
  • CSS 实现字体颜色渐变
  • 【软考网工笔记】计算机基础理论与安全——网络安全
  • JS数组转字符串(3种方法)
  • 云计算安全需求分析与安全防护工程
  • C/C++的printf会调用malloc()
  • spring mvc源码学习笔记之五
  • 3272 小蓝的漆房
  • MySQL使用触发器进行备份
  • 数据结构与算法-顺序表
  • OpenAI CEO 奥特曼发长文《反思》
  • Shell编程详解
  • 跨站脚本攻击(XSS)详解
  • 03-QT中的QMainWindow+对话框QDialog
  • c# 中Parallel.ForEach 对其中一个变量进行赋值 引发报错
  • ElasticSearch备考 -- 整体脉络梳理
  • vue Element Ui Upload 上传 点击一个按钮,选择多个文件后直接上传,使用防抖解决多次上传的问题。
  • 【HF设计模式】05-单例模式
  • 运维人员的Python详细学习路线
  • 软件体系结构与设计模式
  • 安徽省地图arcgis数据美化后mxd文件shp格式下载后内容测评
  • MySQL数据库备份与恢复策略