HTML5 是构建网页结构的标准标记语言,它定义了网页的内容和结构。
<!-- 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>
<header>
<h1>网站标题</h1>
<nav>
<ul>
<li><a href="#">首页</a></li>
<li><a href="#">关于</a></li>
<li><a href="#">联系</a></li>
</ul>
</nav>
</header>
<main>
<section>
<h2>内容区域</h2>
<p>这是网页的主要内容。</p>
</section>
</main>
<footer>
<p>© 2024 网站版权</p>
</footer>
</body>
</html>
CSS3 用于描述网页的样式和布局,它控制着网页元素的外观。
/* CSS3 基本样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
line-height: 1.6;
color: #333;
background-color: #f4f4f4;
}
header {
background-color: #333;
color: #fff;
padding: 1rem;
text-align: center;
}
nav ul {
list-style: none;
display: flex;
justify-content: center;
gap: 1rem;
margin-top: 1rem;
}
nav a {
color: #fff;
text-decoration: none;
padding: 0.5rem;
transition: all 0.3s ease;
}
nav a:hover {
background-color: #555;
border-radius: 4px;
}
main {
max-width: 800px;
margin: 2rem auto;
padding: 0 1rem;
}
section {
background-color: #fff;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 1rem;
margin-top: 2rem;
}
JavaScript 是一种脚本语言,用于为网页添加交互功能和动态效果。
// JavaScript 基本功能
// 1. DOM 操作
document.addEventListener('DOMContentLoaded', function() {
// 获取元素
const btn = document.getElementById('btn');
const output = document.getElementById('output');
// 添加事件监听器
btn.addEventListener('click', function() {
output.textContent = '按钮被点击了!';
output.style.color = 'blue';
});
});
// 2. 数据类型和变量
let name = 'John';
const age = 30;
var isStudent = false;
// 3. 函数
function greet(person) {
return `Hello, ${person}!`;
}
// 4. 箭头函数
const sum = (a, b) => a + b;
// 5. 数组操作
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
const evenNumbers = numbers.filter(num => num % 2 === 0);
const sumOfNumbers = numbers.reduce((acc, curr) => acc + curr, 0);
// 6. 对象
const person = {
name: 'Alice',
age: 25,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
React 是 Facebook 开发的一个用于构建用户界面的 JavaScript 库,它采用组件化的开发方式。
// React 组件示例
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
计数器: {count}
);
}
export default Counter;
// React 应用入口
import React from 'react';
import ReactDOM from 'react-dom/client';
import Counter from './Counter';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
);
Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面和单页应用。
// Vue 组件示例
计数器: {{ count }}
// Vue 应用入口
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时,用于构建服务器端应用。
// Node.js 服务器示例
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// 设置响应头
res.setHeader('Content-Type', 'text/html');
// 路由处理
let filePath = '.' + req.url;
if (filePath === './') {
filePath = './index.html';
}
// 读取文件
fs.readFile(filePath, (err, content) => {
if (err) {
// 404 错误
res.writeHead(404);
res.end(`File not found: ${filePath}`);
} else {
// 成功响应
res.writeHead(200);
res.end(content, 'utf-8');
}
});
});
// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Express.js 是一个基于 Node.js 的 Web 应用框架,它提供了简洁而强大的 API 来构建 Web 应用和 API。
// Express.js 服务器示例
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
// 中间件
app.use(express.json());
app.use(express.static('public'));
// 路由
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'John' },
{ id: 2, name: 'Alice' }
]);
});
app.post('/api/users', (req, res) => {
const newUser = req.body;
res.status(201).json(newUser);
});
// 启动服务器
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
MySQL 是一个流行的关系型数据库管理系统,广泛用于 Web 应用开发。
-- MySQL 基本操作
-- 创建数据库
CREATE DATABASE myapp;
-- 使用数据库
USE myapp;
-- 创建表
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 插入数据
INSERT INTO users (name, email, password) VALUES
('John Doe', 'john@example.com', 'password123'),
('Alice Smith', 'alice@example.com', 'password456');
-- 查询数据
SELECT * FROM users;
SELECT * FROM users WHERE id = 1;
-- 更新数据
UPDATE users SET name = 'John Smith' WHERE id = 1;
-- 删除数据
DELETE FROM users WHERE id = 2;
MongoDB 是一个 NoSQL 数据库,它使用文档存储格式,适合处理大量非结构化数据。
// MongoDB 基本操作 (使用 Node.js 驱动)
const { MongoClient } = require('mongodb');
async function main() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db('myapp');
const usersCollection = db.collection('users');
// 插入文档
await usersCollection.insertOne({
name: 'John Doe',
email: 'john@example.com',
age: 30,
hobbies: ['reading', 'coding']
});
// 查询文档
const user = await usersCollection.findOne({ name: 'John Doe' });
console.log('Found user:', user);
// 更新文档
await usersCollection.updateOne(
{ name: 'John Doe' },
{ $set: { age: 31 } }
);
// 删除文档
await usersCollection.deleteOne({ name: 'John Doe' });
} finally {
await client.close();
}
}
main().catch(console.error);
MERN 栈是指 MongoDB、Express.js、React 和 Node.js 的组合,用于构建全栈 JavaScript 应用。
// MERN 项目结构 myapp/ ├── backend/ │ ├── app.js # Express 应用入口 │ ├── routes/ # API 路由 │ ├── controllers/ # 请求处理逻辑 │ ├── models/ # MongoDB 模型 │ └── middleware/ # 中间件 ├── frontend/ │ ├── public/ # 静态文件 │ ├── src/ │ │ ├── components/ # React 组件 │ │ ├── pages/ # 页面组件 │ │ ├── services/ # API 服务 │ │ ├── App.js # 主应用组件 │ │ └── index.js # 应用入口 │ └── package.json └── package.json
Web 应用可以部署在各种平台上,包括云服务和传统服务器。
持续集成和持续部署 (CI/CD) 可以自动化构建、测试和部署过程。
# GitHub Actions 配置示例 (.github/workflows/deploy.yml)
name: Deploy to Heroku
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
- name: Deploy to Heroku
uses: akhileshns/heroku-deploy@v3.12.12
with:
heroku_api_key: ${{ secrets.HEROKU_API_KEY }}
heroku_app_name: "your-app-name"
heroku_email: "your-email@example.com"
branch: main