← 返回主页

Web开发速查表

HTML · CSS · JavaScript 快速参考

HTML 基础

文档结构

<!-- HTML5 文档模板 -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面标题</title>
</head>
<body>
    <!-- 页面内容 -->
</body>
</html>

常用标签

<h1>标题1</h1> <!-- 到 h6 -->
<p>段落</p>
<a href="链接地址">链接文字</a>
<img src="图片路径" alt="描述">
<div>容器</div>
<span>行内容器</span>
<ul><li>无序列表</li></ul>
<ol><li>有序列表</li></ol>
语义化标签:<header>, <nav>, <main>, <article>, <section>, <footer> 能提高SEO和可访问性

CSS 基础

选择器

/* 元素选择器 */
p { color: red; }

/* 类选择器 */
.my-class { color: blue; }

/* ID选择器 */
#my-id { color: green; }

/* 属性选择器 */
[href="https"] { color: orange; }

/* 组合选择器 */
div p { }       /* 后代 */
div > p { }      /* 子元素 */
div + p { }      /* 相邻兄弟 */
div ~ p { }      /* 兄弟元素 */

常用属性

display: block | inline | flex | grid | none;
position: static | relative | absolute | fixed | sticky;
margin: 10px;     /* 外边距 */
padding: 10px;    /* 内边距 */
border: 1px solid #000;
border-radius: 5px;
background: linear-gradient(to right, red, blue);
box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
transition: all 0.3s ease;

Flexbox 布局

.container {
    display: flex;
    justify-content: center;  /* 主轴对齐 */
    align-items: center;      /* 交叉轴对齐 */
    flex-direction: row;       /* 方向 */
    flex-wrap: wrap;           /* 换行 */
}

.item {
    flex: 1;  /* flex-grow flex-shrink flex-basis */
}

JavaScript 基础

变量与数据类型

let name = "张三";      // 可变变量
const PI = 3.14159;      // 常量
var old = true;         // 旧方式,不推荐

// 数据类型
typeof "hello";    // "string"
typeof 42;         // "number"
typeof true;        // "boolean"
typeof [1,2,3];      // "object"
typeof {a:1};       // "object"
typeof function(){}; // "function"

数组操作

const arr = [1, 2, 3, 4, 5];

// 遍历
arr.forEach(item => console.log(item));

// 变换
const doubled = arr.map(x => x * 2);

// 过滤
const even = arr.filter(x => x % 2 === 0);

// 归约
const sum = arr.reduce((acc, x) => acc + x, 0);

// 查找
const found = arr.find(x => x > 2);  // 3
const hasThree = arr.includes(3);  // true

异步操作

// Promise
fetch('/api/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

// Async/Await
async function getData() {
    try {
        const response = await fetch('/api/data');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

DOM 操作

// 选择元素
document.querySelector('#myId');
document.querySelectorAll('.myClass');

// 修改内容
element.textContent = "新内容";
element.innerHTML = "<b>HTML内容</b>";

// 修改样式
element.style.color = 'red';
element.classList.add('active');
element.classList.remove('hidden');

// 事件监听
button.addEventListener('click', () => {
    console.log('被点击了!');
});
使用 innerHTML 时要注意 XSS 攻击,尽量使用 textContent 或设置 innerHTML 前进行过滤

Python 后端:FastAPI + Uvicorn

FastAPI 简介

现代、快速、高性能的 Python Web 框架,基于标准 Python 类型提示

# 安装
pip install fastapi uvicorn

# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

启动服务

# 开发模式启动(带热重载)
uvicorn main:app --reload

# 指定端口
uvicorn main:app --host 0.0.0.0 --port 8000 --reload

# 生产模式启动(4个worker)
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

# 访问地址
# API: http://localhost:8000
# 文档: http://localhost:8000/docs (Swagger UI)
# 备用文档: http://localhost:8000/redoc

请求方法与参数

from fastapi import FastAPI, Query, Path, Body
from pydantic import BaseModel

class UserCreate(BaseModel):
    name: str
    age: int = 18

# POST 请求(请求体)
@app.post("/users")
def create_user(user: UserCreate):
    return {"name": user.name, "age": user.age}

# GET 请求(查询参数)
@app.get("/search")
def search(q: str = Query(None, min_length=1),
            limit: int = 10):
    return {"query": q, "limit": limit}

# PUT 请求(更新)
@app.put("/users/{user_id}")
def update_user(user_id: int, user: UserCreate):
    return {"user_id": user_id, "updated": True}

# DELETE 请求
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
    return {"user_id": user_id, "deleted": True}

中间件与静态文件

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse

app = FastAPI()

# CORS 跨域配置
app.add_middleware(CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"])

# 全局异常处理
@app.exception_handler(Exception)
async def global_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={"error": str(exc)})

# 静态文件
app.mount("/static", StaticFiles(directory="static"))

Uvicorn 配置详解

# uvicorn.conf.py(推荐用配置文件启动)
workers = 4
host = "0.0.0.0"
port = 8000
reload = True     # 开发时开启热重载
log_level = "info"

# 使用配置文件启动
uvicorn main:app --config uvicorn.conf.py

# 常用参数速查
# --reload          代码改动自动重启(仅开发)
# --workers N       进程数(生产建议 CPU核心数*2+1)
# --host            监听地址(0.0.0.0=所有网卡)
# --port            监听端口
# --ssl-keyfile     HTTPS 私钥
# --ssl-certfile    HTTPS 证书
# --limit-concurrency  最大并发连接数
# --timeout-keep-alive  连接保活超时(秒)

生产部署(Nginx + Uvicorn)

# 1. 使用 systemd 管理服务
# /etc/systemd/system/fastapi.service
[Unit]
Description=FastAPI App
After=network.target

[Service]
User=www-data
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/uvicorn main:app \
    --host 127.0.0.1 --port 8000 --workers 4
Restart=always

[Install]
WantedBy=multi-user.target

# 2. Nginx 反向代理
# server {
#     listen 80;
#     server_name example.com;
#     location / {
#         proxy_pass http://127.0.0.1:8000;
#         proxy_set_header Host $host;
#         proxy_set_header X-Real-IP $remote_addr;
#     }
#     location /static {
#         alias /var/www/app/static;
#     }
# }

# 3. 启动服务
sudo systemctl enable fastapi
sudo systemctl start fastapi
💡 FastAPI 自带 Swagger UI 和 ReDoc 文档,访问 /docs 和 /redoc 即可查看。开发 API 时无需额外工具!