欢迎来到 HTTP 服务器的世界!以下内容将帮助你快速上手:
🚀 基础示例
# Python 3 示例(使用 http.server 模块)
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"<h1>你好,这是入门示例!</h1>")
server = HTTPServer(('localhost', 8000), SimpleHandler)
print("Server running on http://localhost:8000")
server.serve_forever()
🧭 路由处理
- 使用
path
参数匹配请求路径 - 示例:
/examples/getting-started
会触发此页面 - 可扩展至
/examples/quick-start
获取更简单示例
🧩 中间件使用
// Node.js 示例(使用 express)
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log(`处理 ${req.path}`);
next();
});
app.get('/examples/getting-started', (req, res) => {
res.send('中间件已生效!');
});
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});