Node.js中Express框架入门教程

什么是Express.js?

Express.js是Node.js最受欢迎的Web应用框架之一,被称为"快速、开放、极简的Web框架"。它为构建Web应用程序和API提供了一套丰富的功能,同时保持了轻量级和灵活性。

为什么选择Express?

  • 简单易学:API简洁明了,学习曲线平缓
  • 灵活性强:不强制特定的项目结构,开发者可以自由组织代码
  • 中间件丰富:拥有庞大的中间件生态系统
  • 性能优秀:轻量级设计,运行效率高
  • 社区活跃:文档完善,社区支持强大

环境准备

在开始之前,确保您的系统已安装:

  • Node.js(版本12或更高)
  • npm(通常随Node.js一起安装)

检查安装版本:

复制代码
node --version
npm --version

安装Express

创建新项目

复制代码
# 创建项目目录
mkdir my-express-app
cd my-express-app

# 初始化npm项目
npm init -y

# 安装Express
npm install express

使用Express生成器(可选)

复制代码
# 全局安装Express生成器
npm install -g express-generator

# 创建项目
express --view=ejs my-app
cd my-app
npm install

创建第一个Express应用

让我们创建一个简单的"Hello World"应用:

基础示例

复制代码
// app.js
const express = require('express');
const app = express();
const port = 3000;

// 定义路由
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});

运行应用:

复制代码
node app.js

访问 http://localhost:3000,您将看到"Hello World!"消息。

路由基础

路由决定了应用程序如何响应客户端对特定端点的请求。

HTTP方法

复制代码
// GET请求
app.get('/users', (req, res) => {
  res.send('获取用户列表');
});

// POST请求
app.post('/users', (req, res) => {
  res.send('创建新用户');
});

// PUT请求
app.put('/users/:id', (req, res) => {
  res.send(`更新用户 ${req.params.id}`);
});

// DELETE请求
app.delete('/users/:id', (req, res) => {
  res.send(`删除用户 ${req.params.id}`);
});

路由参数

复制代码
// 路径参数
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`用户ID: ${userId}`);
});

// 多个参数
app.get('/users/:userId/posts/:postId', (req, res) => {
  const { userId, postId } = req.params;
  res.json({ userId, postId });
});

// 查询参数
app.get('/search', (req, res) => {
  const { q, page, limit } = req.query;
  res.json({ query: q, page, limit });
});

路由模式匹配

复制代码
// 通配符
app.get('/ab*cd', (req, res) => {
  res.send('匹配 abcd, abxcd, abRANDOMcd 等');
});

// 可选参数
app.get('/products/:id?', (req, res) => {
  if (req.params.id) {
    res.send(`产品ID: ${req.params.id}`);
  } else {
    res.send('所有产品');
  }
});

中间件详解

中间件是Express的核心概念,它是在请求-响应循环中执行的函数。

应用级中间件

复制代码
// 全局中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next(); // 调用next()继续执行下一个中间件
});

// 特定路径的中间件
app.use('/api', (req, res, next) => {
  console.log('API请求');
  next();
});

内置中间件

复制代码
// 解析JSON请求体
app.use(express.json());

// 解析URL编码的请求体
app.use(express.urlencoded({ extended: true }));

// 提供静态文件服务
app.use(express.static('public'));

第三方中间件

复制代码
# 安装常用中间件
npm install morgan cors helmet compression

const morgan = require('morgan');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');

// 日志中间件
app.use(morgan('combined'));

// 启用CORS
app.use(cors());

// 安全中间件
app.use(helmet());

// 压缩响应
app.use(compression());

错误处理中间件

复制代码
// 错误处理中间件必须有四个参数
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    error: '服务器内部错误',
    message: err.message
  });
});

模板引擎

Express支持多种模板引擎,如EJS、Pug、Handlebars等。

使用EJS

复制代码
npm install ejs

// 设置模板引擎
app.set('view engine', 'ejs');
app.set('views', './views');

// 渲染模板
app.get('/profile/:name', (req, res) => {
  res.render('profile', { 
    username: req.params.name,
    title: '用户资料'
  });
});

创建模板文件 views/profile.ejs

复制代码
<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1>欢迎, <%= username %>!</h1>
    <p>这是您的个人资料页面。</p>
</body>
</html>

完整示例:简单的博客API

复制代码
const express = require('express');
const app = express();
const port = 3000;

// 中间件
app.use(express.json());
app.use(express.static('public'));

// 模拟数据
let posts = [
  { id: 1, title: '第一篇文章', content: '这是第一篇文章的内容' },
  { id: 2, title: '第二篇文章', content: '这是第二篇文章的内容' }
];

// 获取所有文章
app.get('/api/posts', (req, res) => {
  res.json(posts);
});

// 获取特定文章
app.get('/api/posts/:id', (req, res) => {
  const post = posts.find(p => p.id === parseInt(req.params.id));
  if (!post) {
    return res.status(404).json({ error: '文章未找到' });
  }
  res.json(post);
});

// 创建新文章
app.post('/api/posts', (req, res) => {
  const { title, content } = req.body;
  
  if (!title || !content) {
    return res.status(400).json({ error: '标题和内容不能为空' });
  }
  
  const newPost = {
    id: posts.length + 1,
    title,
    content
  };
  
  posts.push(newPost);
  res.status(201).json(newPost);
});

// 更新文章
app.put('/api/posts/:id', (req, res) => {
  const postIndex = posts.findIndex(p => p.id === parseInt(req.params.id));
  
  if (postIndex === -1) {
    return res.status(404).json({ error: '文章未找到' });
  }
  
  const { title, content } = req.body;
  posts[postIndex] = { ...posts[postIndex], title, content };
  
  res.json(posts[postIndex]);
});

// 删除文章
app.delete('/api/posts/:id', (req, res) => {
  const postIndex = posts.findIndex(p => p.id === parseInt(req.params.id));
  
  if (postIndex === -1) {
    return res.status(404).json({ error: '文章未找到' });
  }
  
  posts.splice(postIndex, 1);
  res.status(204).send();
});

// 错误处理
app.use((req, res) => {
  res.status(404).json({ error: '页面未找到' });
});

app.listen(port, () => {
  console.log(`博客API运行在 http://localhost:${port}`);
});

最佳实践

项目结构建议

复制代码
my-app/
├── public/          # 静态文件
├── views/           # 模板文件
├── routes/          # 路由模块
├── middleware/      # 自定义中间件
├── models/          # 数据模型
├── controllers/     # 控制器
├── config/          # 配置文件
├── app.js          # 主应用文件
└── package.json

路由模块化

复制代码
// routes/users.js
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.send('用户列表');
});

router.get('/:id', (req, res) => {
  res.send(`用户ID: ${req.params.id}`);
});

module.exports = router;

// 在主应用中使用
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);

环境配置

复制代码
// 使用环境变量
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'development';

if (env === 'development') {
  app.use(morgan('dev'));
}

下一步学习

掌握了Express基础后,您可以继续学习:

  • 数据库集成:MongoDB (Mongoose)、MySQL (Sequelize)
  • 身份验证:JWT、Passport.js
  • API文档:Swagger/OpenAPI
  • 测试:Jest、Supertest
  • 部署:Docker、Heroku、AWS

总结

Express.js是一个功能强大而又简洁的Web框架,非常适合快速构建Web应用程序和API。通过掌握路由、中间件、模板引擎等核心概念,您就能够开发出功能丰富的Web应用。

记住Express的哲学:保持简单,但提供足够的灵活性让开发者能够构建复杂的应用程序。随着经验的积累,您将能够利用Express的强大功能构建更加复杂和优雅的Web解决方案。

相关资源

相关推荐
Java 码农2 小时前
nodejs mongodb基础
数据库·mongodb·node.js
爱心发电丶10 小时前
NodeSSh 实现前端自动部署:服务端编译和本地编译
node.js
Face10 小时前
Node.js全栈基石(壹)
前端·node.js
mosen86812 小时前
易混淆的CommonJS和ESM(ES Module)及它们区别
javascript·node.js·express
袁袁袁袁满1 天前
基于nvm安装管理多个node.js版本切换使用(附上详细安装使用图文教程+nvm命令大全)
运维·node.js·nvm·nvm安装·多个node.js版本切换使用·nvm命令大全·node.js安装
Q_Q5110082851 天前
python的校园研招网系统
开发语言·spring boot·python·django·flask·node.js·php
棒棒的唐1 天前
nodejs安装后 使用npm 只能在cmd 里使用 ,但是不能在poowershell使用,只能用npm.cmd
前端·npm·node.js
G等你下课1 天前
基于MCP构建一个智能助手
前端·node.js·mcp
JSPanda1 天前
Webpack插件开发避坑指南:三招制服Dev Server兼容性
webpack·node.js