HTTP:每个 Web 开发人员都必须掌握的协议
您是否正在构建 Web 应用程序,但苦于 API 集成问题?了解 HTTP 是现代 Web 开发的基础,但经常被忽视。本指南将把您从普通的 API 用户转变为自信的 HTTP 专家。
您将学到什么
本指南适用于哪些人
目录
实践练习
更多资源
为什么 HTTP 对 Web 开发如此重要
每次网络交互都以 HTTP 为基础。了解 HTTP 不仅仅意味着进行 API 调用,还意味着构建可扩展的、强大、安全且性能卓越的网络应用程序。
HTTP(超文本传输协议)是网络通信的支柱。本指南通过实际示例探索其核心方法。

对性能的影响
安全注意事项
专业发展
核心概念
HTTP 协议基础知识
请求/响应周期
**客户端发起请求**
**服务器处理请求**
**服务器发送响应**
标题和正文
通用标头
Authorization: Bearer token123 Content-Type: application/json Accept: application/json Cache-Control: no-cache
车身结构
{ "request": { "data": "Example request payload" }, "response": { "data": "Example response payload" } }
验证
// Middleware example const authenticate = async (req, res, next) => { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'Authentication required' }); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; next(); } catch (error) { res.status(401).json({ error: 'Invalid token' }); } };
先决条件
在深入了解 HTTP 方法之前,请确保您已:
技术要求:
所需知识:
实际应用
常见实现:
常见 HTTP 状态代码
// Success Codes 200 OK // Successful GET 201 Created // Successful POST 204 No Content // Successful DELETE // Client Error Codes 400 Bad Request // Invalid syntax 401 Unauthorized // Authentication required 404 Not Found // Resource doesn't exist // Server Error Codes 500 Internal Error // Server-side error
HTTP 方法深入探究
GET 方法
graph LR Client-->|GET /products|Server Server-->|200 + Products|Client
概念
GET 请求检索数据而不修改服务器状态。它们应该是:
实施说明
// GET /products/:id // Purpose: Retrieve single product // Security: Validate ID format // Error handling: 404 if not found app.get("/products/:id", async (req, res) => { try { const product = await Product.findById(req.params.id); if (!product) { return res.status(404).json({ error: "Product not found" }); } res.json(product); } catch (error) { handleError(error, res); } });
POST 方法
graph LR Client-->|POST /products|Server Server-->|201 Created|Client
概念
POST 创建新资源。它应该:
执行
app.post("/products", async (req, res) => { try { // Validation const { name, price } = req.body; if (!name || !price) { return res.status(400).json({ error: "Missing required fields" }); } // Create resource const product = new Product(req.body); await product.save(); // Return created resource res.status(201).json({ message: "Product created", product }); } catch (error) { handleError(error, res); } });
PUT 方法
graph LR Client-->|PUT /products/123|Server Server-->|200 OK|Client
概念
PUT 替换整个资源。应该是:
执行
app.put("/products/:id", async (req, res) => { try { const product = await Product.findByIdAndUpdate( req.params.id, req.body, { new: true, overwrite: true } ); if (!product) { return res.status(404).json({ error: "Product not found" }); } res.json(product); } catch (error) { handleError(error, res); } });
PATCH 方法
graph LR Client-->|PATCH /products/123|Server Server-->|200 OK|Client
概念
PATCH 部分更新资源。它应该:
执行
app.patch("/products/:id", async (req, res) => { try { // Validate allowed updates const updates = Object.keys(req.body); const allowedUpdates = ['name', 'price', 'description']; const isValidOperation = updates.every(update => allowedUpdates.includes(update) ); if (!isValidOperation) { return res.status(400).json({ error: "Invalid updates" }); } const product = await Product.findByIdAndUpdate( req.params.id, req.body, { new: true, runValidators: true } ); if (!product) { return res.status(404).json({ error: "Product not found" }); } res.json(product); } catch (error) { handleError(error, res); } });
DELETE 方法
graph LR Client-->|DELETE /products/123|Server Server-->|204 No Content|Client
概念
DELETE 删除资源。它应该:
执行
app.delete("/products/:id", async (req, res) => { try { const product = await Product.findByIdAndDelete(req.params.id); if (!product) { return res.status(404).json({ error: "Product not found" }); } res.status(204).send(); } catch (error) { handleError(error, res); } });
高级主题
缓存策略
浏览器缓存
// Setting cache headers app.get('/static-content', (req, res) => { res.set({ 'Cache-Control': 'public, max-age=86400', 'ETag': 'W/"123-abc"' }); res.send(content); });
Redis 缓存示例
const Redis = require('redis'); const redis = Redis.createClient(); // Cache middleware const cacheMiddleware = async (req, res, next) => { const key = `cache:${req.originalUrl}`; const cached = await redis.get(key); if (cached) { return res.json(JSON.parse(cached)); } res.sendResponse = res.json; res.json = async (body) => { await redis.setEx(key, 3600, JSON.stringify(body)); res.sendResponse(body); }; next(); };
错误处理模式
集中错误处理程序
// error-handler.js class AppError extends Error { constructor(statusCode, message) { super(message); this.statusCode = statusCode; this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error'; Error.captureStackTrace(this, this.constructor); } } const errorHandler = (err, req, res, next) => { err.statusCode = err.statusCode || 500; if (process.env.NODE_ENV === 'development') { res.status(err.statusCode).json({ status: err.status, error: err, message: err.message, stack: err.stack }); } else { // Production error response if (err.isOperational) { res.status(err.statusCode).json({ status: err.status, message: err.message }); } else { console.error('ERROR 💥', err); res.status(500).json({ status: 'error', message: 'Something went wrong' }); } } };
速率限制
Express 速率限制器
const rateLimit = require('express-rate-limit'); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // limit each IP to 100 requests per windowMs message: 'Too many requests, please try again later', standardHeaders: true, legacyHeaders: false }); // Apply to all requests app.use(limiter); // Apply to specific routes app.use('/api', limiter);
CORS 配置
const cors = require('cors'); // Basic CORS app.use(cors()); // Advanced CORS configuration const corsOptions = { origin: ['https://yourdomain.com', 'https://api.yourdomain.com'], methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], allowedHeaders: ['Content-Type', 'Authorization'], exposedHeaders: ['X-Total-Count'], credentials: true, maxAge: 3600 }; app.use(cors(corsOptions));
实践练习
构建 RESTful API
练习 1:用户管理 API
创建一个完整的用户管理 CRUD API,要求如下:
// Sample starter code const express = require('express'); const router = express.Router(); router.post('/users', validateUser, async (req, res) => { // Implementation exercise }); // Additional routes to implement router.get('/users'); router.get('/users/:id'); router.put('/users/:id'); router.delete('/users/:id');
实现身份验证
练习 2:JWT 身份验证
使用以下方式实现基于 JWT 的身份验证:
// Authentication middleware exercise const authenticateToken = async (req, res, next) => { // Implementation exercise }; // Token generation exercise const generateTokens = (user) => { // Implementation exercise };
处理文件上传
练习 3:分段文件上传
实现一个文件上传系统:
const multer = require('multer'); // Storage configuration exercise const storage = multer.diskStorage({ // Implementation exercise }); // File filter exercise const fileFilter = (req, file, cb) => { // Implementation exercise };
性能优化
练习 4:API 优化
使用以下方式优化现有 API:
// Compression middleware const compression = require('compression'); app.use(compression()); // Pagination exercise const paginate = (model) => async (req, res, next) => { // Implementation exercise };
更多资源
推荐工具
API 开发
监控 $ 调试
文档
其他阅读材料
规格与标准
图书
在线课程
社区资源
论坛和讨论
开源项目
API 设计指南
了解最新动态: