express的介绍,简单使用

177 阅读1分钟

Express 框架的简要介绍和简单使用方法总结:


🌟 什么是 Express?

Express 是一个基于 Node.js 平台的 Web 应用开发框架,用于快速搭建 Web 应用和 API。它是轻量、灵活的,拥有大量的中间件和插件,极大地简化了服务器端开发。

官网地址:expressjs.com/


🧰 安装 Express

npm init -y        # 初始化项目
npm install express --save

📦 简单示例:Hello World

// 引入 express 模块
const express = require('express');
const app = express();

// 设置端口
const port = 3000;

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

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

📌 常用功能简要说明

1. 路由

app.get('/hello', (req, res) => {
  res.send('Hello from GET!');
});

app.post('/submit', (req, res) => {
  res.send('Data received via POST!');
});

2. 中间件

app.use(express.json()); // 解析 JSON 请求体
app.use(express.static('public')); // 提供静态资源

3. 路由参数和查询参数

app.get('/user/:id', (req, res) => {
  res.send(`User ID is ${req.params.id}`);
});

app.get('/search', (req, res) => {
  res.send(`You searched for ${req.query.q}`);
});

🔚 总结

功能说明
快速搭建几行代码就能启动服务器
RESTful支持支持 GET、POST、PUT、DELETE 等
中间件机制灵活插入处理逻辑
模块丰富社区庞大、插件众多