Cookie机制与静态服务器实现详解

99 阅读2分钟

Cookie机制与静态服务器实现详解

项目结构概览

cookie-demo/
├── public/              # 前端资源目录
│   ├── index.html       # 主页面
│   ├── script.js        # 客户端脚本
│   └── style.css        # 样式文件
├── app.js               # ES6模块化HTTP服务器
└── sever.js             # 静态资源服务器

核心技术解析

1. 模块化方案对比

javascript
// ES6模块化特点
import http from "http";

const sever = http.createServer((req, res) => {
  // 响应简单文本
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, World! http://localhost:1234\n");
});
javascript
// CommonJS模块化特点
const http = require("http");
const fs = require("fs");
const path = require("path");

// 请求处理逻辑
server = http.createServer((req, res) => {
  // 路由处理...
});

2. 静态服务器实现要点

javascript
// 改进后的静态服务器核心逻辑
function serveStatic(res, filePath, contentType) {
  fs.readFile(filePath, (err, content) => {
    if (err) {
      res.writeHead(500);
      return res.end("Server Error");
    }
    res.writeHead(200, { "Content-Type": contentType });
    res.end(content);
  });
}

Cookie机制实现

1. 服务端设置Cookie

javascript
// 在响应头中添加Cookie
res.setHeader('Set-Cookie', [
  'user_token=abc123',
  'Max-Age=3600',
  'Path=/',
  'HttpOnly'
]);

2. 客户端读取Cookie

javascript
// Cookie解析函数
function parseCookies() {
  return document.cookie
    .split('; ')
    .reduce((cookies, cookie) => {
      const [name, value] = cookie.split('=');
      cookies[name] = value;
      return cookies;
    }, {});
}

// 使用示例
const cookies = parseCookies();
console.log('User Token:', cookies.user_token);

服务器功能增强

1. MIME类型支持扩展

javascript
// 添加更多MIME类型
const MIME_TYPES = {
  '.html': 'text/html',
  '.css': 'text/css',
  '.js': 'text/javascript',
  '.jpg': 'image/jpeg',
  '.png': 'image/png'
};

2. 安全性增强

javascript
// 添加安全响应头
res.writeHead(200, {
  'Content-Type': contentType,
  'X-Content-Type-Options': 'nosniff',
  'X-Frame-Options': 'DENY'
});

运行与验证

启动服务器

bash
# 启动ES6模块服务器
node --experimental-modules app.js

# 启动静态服务器
node sever.js

访问测试

  1. 访问 http://localhost:1235 查看主页面
  2. 打开开发者工具检查Network面板中的Cookie信息
  3. 查看控制台输出的请求日志
  4. 测试不同文件类型的访问(HTML/CSS/JS)

性能优化建议

  1. 添加Gzip压缩支持
  2. 实现ETag缓存机制
  3. 使用流式传输大文件
  4. 添加连接保持(keep-alive)

安全最佳实践

  1. 始终启用HttpOnly防止XSS攻击
  2. 对敏感数据使用Secure标记
  3. 添加SameSite属性防止CSRF
  4. 设置合适的Max-Age过期时间