Express
Express 是一个轻量级、灵活的 Node.js Web 框架,以其简单易用和高度可扩展著称。它提供了简洁的 API 设计,支持中间件机制,能快速构建 RESTful API 或全栈应用。Express 拥有丰富的插件生态,可轻松集成数据库、身份验证等功能,同时保持高性能和低学习成本,是 Node.js 开发者的首选框架之一。
本指南介绍如何在 CloudBase HTTP 云函数上部署 Express 应用程序。
前置条件
在开始之前,请确保您已经:
- 安装了 Node.js 18.x 或更高版本
- 拥有腾讯云账号并开通了 CloudBase 服务
- 了解基本的 Node.js 和 Express 开发知识
第一步:创建 Express 应用
💡 提示:如果您已经有一个 Express 应用,可以跳过此步骤。
创建项目目录
mkdir express-cloudbase
cd express-cloudbase
使用 Express Generator 创建应用
# 使用 Express Generator 创建应用
npx express-generator --view=pug express-app
# 进入项目目录
cd express-app
# 安装依赖
npm install
这将创建一个使用 Pug 作为视图引擎的 Express 应用程序。
本地测试应用
启动开发服务器:
npm start
打开浏览器访问 http://localhost:3000,您应该能看到 Express 欢迎页面。
第二步:添加 API 路由
让我们创建一个 RESTful API 来演示 Express 的功能。
创建用户路由
在 routes 目录下创建 users.js 文件:
const express = require("express");
const router = express.Router();
// 模拟用户数据
const users = [
{ id: 1, name: "zhangsan", email: "zhangsan@example.com" },
{ id: 2, name: "lisi", email: "lisi@example.com" },
{ id: 3, name: "wangwu", email: "wangwu@example.com" },
];
/* GET users listing */
router.get("/", function (req, res, next) {
const { page = 1, limit = 10 } = req.query;
const startIndex = (page - 1) * limit;
const endIndex = startIndex + parseInt(limit);
const paginatedUsers = users.slice(startIndex, endIndex);
res.json({
success: true,
data: {
total: users.length,
page: parseInt(page),
limit: parseInt(limit),
items: paginatedUsers,
},
});
});
/* GET user by ID */
router.get("/:id", function (req, res, next) {
const userId = parseInt(req.params.id);
const user = users.find((u) => u.id === userId);
if (!user) {
return res.status(404).json({
success: false,
message: "User not found",
});
}
res.json({
success: true,
data: user,
});
});
/* POST create user */
router.post("/", function (req, res, next) {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({
success: false,
message: "Name and email are required",
});
}
const newUser = {
id: users.length + 1,
name,
email,
};
users.push(newUser);
res.status(201).json({
success: true,
data: newUser,
});
});
module.exports = router;