第五章:HTTP服务器与Web开发
5.1 创建HTTP服务器
const http = require('http');
const server = http.createServer((req, res) => {
console.log('收到请求:', req.url);
console.log('请求方法:', req.method);
res.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8'
});
res.end('Hello, Node.js HTTP Server!');
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
5.2 处理不同路由
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
if (pathname === '/') {
res.writeHead(200);
res.end(JSON.stringify({ message: '首页' }));
} else if (pathname === '/users') {
if (req.method === 'GET') {
res.writeHead(200);
res.end(JSON.stringify({
users: [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' }
]
}));
} else if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(201);
res.end(JSON.stringify({
message: '用户创建成功',
data: data
}));
});
}
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: '页面未找到' }));
}
});
server.listen(3000);
5.3 静态文件服务
const http = require('http');
const fs = require('fs').promises;
const path = require('path');
const PUBLIC_DIR = path.join(__dirname, 'public');
const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg'
};
const server = http.createServer(async (req, res) => {
try {
let filePath = path.join(PUBLIC_DIR, req.url === '/' ? 'index.html' : req.url);
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
const content = await fs.readFile(filePath);
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
} catch (err) {
if (err.code === 'ENOENT') {
res.writeHead(404);
res.end('File not found');
} else {
res.writeHead(500);
res.end('Server error');
}
}
});
server.listen(3000);
5.4 RESTful API设计
const http = require('http');
const url = require('url');
let users = [
{ id: 1, name: '张三', email: 'zhangsan@example.com' },
{ id: 2, name: '李四', email: 'lisi@example.com' }
];
let nextId = 3;
function parseBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch (err) {
reject(err);
}
});
});
}
const server = http.createServer(async (req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
const method = req.method;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
if (method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
if (pathname === '/api/users') {
switch (method) {
case 'GET':
res.writeHead(200);
res.end(JSON.stringify({ data: users }));
break;
case 'POST':
try {
const body = await parseBody(req);
const newUser = {
id: nextId++,
name: body.name,
email: body.email
};
users.push(newUser);
res.writeHead(201);
res.end(JSON.stringify({ data: newUser }));
} catch (err) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Invalid data' }));
}
break;
default:
res.writeHead(405);
res.end(JSON.stringify({ error: 'Method not allowed' }));
}
} else if (pathname.startsWith('/api/users/')) {
const userId = parseInt(pathname.split('/')[3]);
const user = users.find(u => u.id === userId);
if (!user) {
res.writeHead(404);
res.end(JSON.stringify({ error: 'User not found' }));
return;
}
switch (method) {
case 'GET':
res.writeHead(200);
res.end(JSON.stringify({ data: user }));
break;
case 'PUT':
const body = await parseBody(req);
Object.assign(user, body);
res.writeHead(200);
res.end(JSON.stringify({ data: user }));
break;
case 'DELETE':
users = users.filter(u => u.id !== userId);
res.writeHead(200);
res.end(JSON.stringify({ message: 'Deleted' }));
break;
}
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Not found' }));
}
});
server.listen(3000);