Search K
Appearance
Appearance
📊 SEO元描述:2024年最新HTTP头部教程,详解请求头响应头、Content-Type、Authorization、Cache-Control等重要头部字段。包含完整代码示例,适合前端开发者快速掌握HTTP头部使用。
核心关键词:HTTP头部2024、HTTP请求头、HTTP响应头、Content-Type、Authorization、Cache-Control
长尾关键词:HTTP头部有哪些、HTTP头部怎么设置、Content-Type类型、Authorization认证头、HTTP缓存头部
通过本节HTTP头部详解,你将系统性掌握:
HTTP头部是什么?HTTP头部是HTTP消息中的元数据字段,用于传递关于请求或响应的附加信息,也是Web应用功能实现和性能优化的重要工具。
💡 学习建议:HTTP头部是Web开发的重要组成部分,理解常用头部字段有助于构建更好的Web应用
HTTP头部由字段名和字段值组成,用冒号分隔:
// 🎉 HTTP头部基础详解
class HTTPHeadersDemo {
constructor() {
this.explainHeaderStructure();
this.demonstrateHeaderCategories();
this.showHeaderHandling();
}
explainHeaderStructure() {
console.log('=== HTTP头部结构 ===');
const headerStructure = {
format: 'Header-Name: Header-Value',
rules: [
'字段名不区分大小写',
'字段值可能区分大小写',
'多个值用逗号分隔',
'可以有多个同名头部',
'空格和制表符会被忽略'
],
examples: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Set-Cookie': ['sessionId=abc123; Path=/; HttpOnly', 'theme=dark; Path=/']
}
};
console.log('头部格式:', headerStructure.format);
console.log('格式规则:', headerStructure.rules);
console.log('示例头部:', headerStructure.examples);
// 演示头部解析
this.demonstrateHeaderParsing();
}
demonstrateHeaderParsing() {
console.log('=== HTTP头部解析演示 ===');
// HTTP头部解析器
class HeaderParser {
// 解析单个头部
static parseHeader(headerLine) {
const colonIndex = headerLine.indexOf(':');
if (colonIndex === -1) {
throw new Error('无效的头部格式');
}
const name = headerLine.substring(0, colonIndex).trim();
const value = headerLine.substring(colonIndex + 1).trim();
return { name, value };
}
// 解析多个头部
static parseHeaders(headerLines) {
const headers = new Map();
headerLines.forEach(line => {
if (line.trim()) {
const { name, value } = this.parseHeader(line);
const normalizedName = name.toLowerCase();
if (headers.has(normalizedName)) {
// 处理多个同名头部
const existing = headers.get(normalizedName);
if (Array.isArray(existing)) {
existing.push(value);
} else {
headers.set(normalizedName, [existing, value]);
}
} else {
headers.set(normalizedName, value);
}
}
});
return headers;
}
// 解析带参数的头部值
static parseParameterizedValue(value) {
const parts = value.split(';').map(part => part.trim());
const mainValue = parts[0];
const parameters = {};
for (let i = 1; i < parts.length; i++) {
const paramParts = parts[i].split('=');
if (paramParts.length === 2) {
const paramName = paramParts[0].trim();
const paramValue = paramParts[1].trim().replace(/^["']|["']$/g, '');
parameters[paramName] = paramValue;
}
}
return { value: mainValue, parameters };
}
// 解析质量值(q值)
static parseQualityValues(value) {
const items = value.split(',').map(item => item.trim());
const parsed = [];
items.forEach(item => {
const parts = item.split(';');
const mediaType = parts[0].trim();
let quality = 1.0;
// 查找q参数
for (let i = 1; i < parts.length; i++) {
const param = parts[i].trim();
if (param.startsWith('q=')) {
quality = parseFloat(param.substring(2)) || 1.0;
break;
}
}
parsed.push({ mediaType, quality });
});
// 按质量值排序
return parsed.sort((a, b) => b.quality - a.quality);
}
}
// 演示头部解析
const sampleHeaders = [
'Content-Type: application/json; charset=utf-8',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Cache-Control: no-cache, no-store, must-revalidate',
'Set-Cookie: sessionId=abc123; Path=/; HttpOnly',
'Set-Cookie: theme=dark; Path=/'
];
const parsedHeaders = HeaderParser.parseHeaders(sampleHeaders);
console.log('解析的头部:', Object.fromEntries(parsedHeaders));
// 演示参数化值解析
const contentType = HeaderParser.parseParameterizedValue('application/json; charset=utf-8');
console.log('Content-Type解析:', contentType);
// 演示质量值解析
const acceptHeader = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
const acceptParsed = HeaderParser.parseQualityValues(acceptHeader);
console.log('Accept头部解析:', acceptParsed);
}
demonstrateHeaderCategories() {
console.log('=== HTTP头部分类 ===');
const headerCategories = {
general: {
name: '通用头部',
description: '适用于请求和响应的头部',
examples: {
'Cache-Control': '缓存控制指令',
'Connection': '连接管理',
'Date': '消息创建时间',
'Pragma': '实现特定指令',
'Trailer': '尾部字段',
'Transfer-Encoding': '传输编码',
'Upgrade': '协议升级',
'Via': '代理信息',
'Warning': '警告信息'
}
},
request: {
name: '请求头部',
description: '仅用于HTTP请求的头部',
examples: {
'Accept': '可接受的内容类型',
'Accept-Charset': '可接受的字符集',
'Accept-Encoding': '可接受的编码',
'Accept-Language': '可接受的语言',
'Authorization': '认证信息',
'Expect': '期望的服务器行为',
'From': '用户邮箱地址',
'Host': '服务器域名',
'If-Match': '条件匹配',
'If-Modified-Since': '条件修改时间',
'If-None-Match': '条件不匹配',
'If-Range': '条件范围',
'If-Unmodified-Since': '条件未修改时间',
'Max-Forwards': '最大转发次数',
'Proxy-Authorization': '代理认证',
'Range': '请求范围',
'Referer': '引用页面',
'TE': '传输编码',
'User-Agent': '用户代理'
}
},
response: {
name: '响应头部',
description: '仅用于HTTP响应的头部',
examples: {
'Accept-Ranges': '接受的范围单位',
'Age': '响应生成时间',
'ETag': '实体标签',
'Location': '重定向位置',
'Proxy-Authenticate': '代理认证方式',
'Retry-After': '重试时间',
'Server': '服务器信息',
'Vary': '变化的头部',
'WWW-Authenticate': '认证方式'
}
},
entity: {
name: '实体头部',
description: '描述消息体的头部',
examples: {
'Allow': '允许的方法',
'Content-Encoding': '内容编码',
'Content-Language': '内容语言',
'Content-Length': '内容长度',
'Content-Location': '内容位置',
'Content-MD5': '内容MD5',
'Content-Range': '内容范围',
'Content-Type': '内容类型',
'Expires': '过期时间',
'Last-Modified': '最后修改时间'
}
}
};
Object.entries(headerCategories).forEach(([category, info]) => {
console.log(`${info.name}:`);
console.log(` 描述: ${info.description}`);
console.log(` 示例:`);
Object.entries(info.examples).forEach(([header, desc]) => {
console.log(` ${header}: ${desc}`);
});
console.log('');
});
}
showHeaderHandling() {
console.log('=== HTTP头部处理 ===');
// HTTP头部管理器
class HeaderManager {
constructor() {
this.defaultHeaders = new Map();
this.setupDefaultHeaders();
}
setupDefaultHeaders() {
// 设置默认请求头
this.defaultHeaders.set('User-Agent', 'MyApp/1.0');
this.defaultHeaders.set('Accept', 'application/json, text/plain, */*');
this.defaultHeaders.set('Accept-Language', 'zh-CN,zh;q=0.9,en;q=0.8');
this.defaultHeaders.set('Accept-Encoding', 'gzip, deflate, br');
}
// 创建请求头
createRequestHeaders(customHeaders = {}) {
const headers = new Map(this.defaultHeaders);
// 合并自定义头部
Object.entries(customHeaders).forEach(([name, value]) => {
headers.set(name, value);
});
return Object.fromEntries(headers);
}
// 处理响应头
processResponseHeaders(response) {
const headers = {};
for (const [name, value] of response.headers.entries()) {
headers[name] = value;
}
return {
contentType: this.getContentType(headers),
contentLength: this.getContentLength(headers),
cacheControl: this.getCacheControl(headers),
etag: headers.etag,
lastModified: headers['last-modified'],
server: headers.server,
date: headers.date
};
}
// 获取内容类型
getContentType(headers) {
const contentType = headers['content-type'];
if (!contentType) return null;
const [mediaType, ...params] = contentType.split(';');
const parameters = {};
params.forEach(param => {
const [key, value] = param.trim().split('=');
if (key && value) {
parameters[key.trim()] = value.trim();
}
});
return {
mediaType: mediaType.trim(),
parameters
};
}
// 获取内容长度
getContentLength(headers) {
const length = headers['content-length'];
return length ? parseInt(length) : null;
}
// 获取缓存控制
getCacheControl(headers) {
const cacheControl = headers['cache-control'];
if (!cacheControl) return null;
const directives = {};
const parts = cacheControl.split(',');
parts.forEach(part => {
const trimmed = part.trim();
const [key, value] = trimmed.split('=');
if (value) {
directives[key] = value;
} else {
directives[key] = true;
}
});
return directives;
}
// 设置认证头
setAuthHeader(token, type = 'Bearer') {
return `${type} ${token}`;
}
// 设置内容类型头
setContentTypeHeader(mediaType, charset = 'utf-8') {
return `${mediaType}; charset=${charset}`;
}
}
// 演示头部管理
const headerManager = new HeaderManager();
// 创建请求头
const requestHeaders = headerManager.createRequestHeaders({
'Authorization': headerManager.setAuthHeader('abc123'),
'Content-Type': headerManager.setContentTypeHeader('application/json')
});
console.log('创建的请求头:', requestHeaders);
// 模拟响应头处理
const mockResponse = {
headers: new Map([
['content-type', 'application/json; charset=utf-8'],
['content-length', '1234'],
['cache-control', 'max-age=3600, public'],
['etag', '"abc123"'],
['server', 'nginx/1.18.0']
])
};
const processedHeaders = headerManager.processResponseHeaders(mockResponse);
console.log('处理的响应头:', processedHeaders);
}
}
// 创建HTTP头部演示实例
const headersDemo = new HTTPHeadersDemo();请求头用于向服务器传递客户端信息和请求参数:
// 🎉 HTTP请求头详解
class RequestHeadersDemo {
constructor() {
this.explainCommonRequestHeaders();
this.demonstrateContentNegotiation();
this.showAuthenticationHeaders();
}
explainCommonRequestHeaders() {
console.log('=== 常用请求头详解 ===');
const commonRequestHeaders = {
'Host': {
description: '指定服务器的域名和端口',
required: true,
example: 'Host: api.example.com:8080',
notes: 'HTTP/1.1中唯一必需的头部'
},
'User-Agent': {
description: '客户端应用程序信息',
required: false,
example: 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
notes: '用于服务器统计和内容适配'
},
'Accept': {
description: '客户端可接受的内容类型',
required: false,
example: 'Accept: text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8',
notes: '支持质量值(q值)排序'
},
'Accept-Language': {
description: '客户端可接受的语言',
required: false,
example: 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
notes: '用于国际化内容协商'
},
'Accept-Encoding': {
description: '客户端可接受的编码方式',
required: false,
example: 'Accept-Encoding: gzip, deflate, br',
notes: '用于内容压缩协商'
},
'Authorization': {
description: '身份认证信息',
required: false,
example: 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
notes: '支持多种认证方案'
},
'Content-Type': {
description: '请求体的内容类型',
required: false,
example: 'Content-Type: application/json; charset=utf-8',
notes: '仅在有请求体时使用'
},
'Content-Length': {
description: '请求体的字节长度',
required: false,
example: 'Content-Length: 1234',
notes: '通常由客户端自动计算'
},
'Referer': {
description: '引用页面的URL',
required: false,
example: 'Referer: https://example.com/page1',
notes: '用于统计和安全检查'
},
'Origin': {
description: '请求的源域',
required: false,
example: 'Origin: https://example.com',
notes: '用于CORS跨域检查'
}
};
Object.entries(commonRequestHeaders).forEach(([header, info]) => {
console.log(`${header}:`);
console.log(` 描述: ${info.description}`);
console.log(` 必需: ${info.required ? '是' : '否'}`);
console.log(` 示例: ${info.example}`);
console.log(` 说明: ${info.notes}`);
console.log('');
});
}
demonstrateContentNegotiation() {
console.log('=== 内容协商演示 ===');
// 内容协商管理器
class ContentNegotiationManager {
// 构建Accept头
buildAcceptHeader(mediaTypes) {
return mediaTypes
.map(type => {
if (typeof type === 'string') {
return type;
}
return `${type.mediaType};q=${type.quality}`;
})
.join(', ');
}
// 构建Accept-Language头
buildAcceptLanguageHeader(languages) {
return languages
.map(lang => {
if (typeof lang === 'string') {
return lang;
}
return `${lang.language};q=${lang.quality}`;
})
.join(', ');
}
// 构建Accept-Encoding头
buildAcceptEncodingHeader(encodings) {
return encodings.join(', ');
}
// 创建内容协商头部
createNegotiationHeaders(preferences) {
const headers = {};
if (preferences.mediaTypes) {
headers['Accept'] = this.buildAcceptHeader(preferences.mediaTypes);
}
if (preferences.languages) {
headers['Accept-Language'] = this.buildAcceptLanguageHeader(preferences.languages);
}
if (preferences.encodings) {
headers['Accept-Encoding'] = this.buildAcceptEncodingHeader(preferences.encodings);
}
return headers;
}
// 解析服务器响应的内容协商结果
parseNegotiationResult(response) {
const result = {};
const contentType = response.headers.get('content-type');
if (contentType) {
result.contentType = contentType;
}
const contentLanguage = response.headers.get('content-language');
if (contentLanguage) {
result.contentLanguage = contentLanguage;
}
const contentEncoding = response.headers.get('content-encoding');
if (contentEncoding) {
result.contentEncoding = contentEncoding;
}
const vary = response.headers.get('vary');
if (vary) {
result.vary = vary.split(',').map(v => v.trim());
}
return result;
}
}
// 演示内容协商
const negotiationManager = new ContentNegotiationManager();
// 创建内容协商头部
const preferences = {
mediaTypes: [
{ mediaType: 'application/json', quality: 1.0 },
{ mediaType: 'application/xml', quality: 0.8 },
{ mediaType: 'text/plain', quality: 0.5 }
],
languages: [
{ language: 'zh-CN', quality: 1.0 },
{ language: 'zh', quality: 0.9 },
{ language: 'en', quality: 0.8 }
],
encodings: ['gzip', 'deflate', 'br']
};
const negotiationHeaders = negotiationManager.createNegotiationHeaders(preferences);
console.log('内容协商头部:', negotiationHeaders);
// 模拟服务器响应
const mockResponse = {
headers: new Map([
['content-type', 'application/json; charset=utf-8'],
['content-language', 'zh-CN'],
['content-encoding', 'gzip'],
['vary', 'Accept, Accept-Language, Accept-Encoding']
])
};
const negotiationResult = negotiationManager.parseNegotiationResult(mockResponse);
console.log('协商结果:', negotiationResult);
}
showAuthenticationHeaders() {
console.log('=== 认证头部演示 ===');
// 认证头部管理器
class AuthenticationHeaderManager {
// Basic认证
createBasicAuth(username, password) {
const credentials = btoa(`${username}:${password}`);
return `Basic ${credentials}`;
}
// Bearer Token认证
createBearerAuth(token) {
return `Bearer ${token}`;
}
// API Key认证
createApiKeyAuth(apiKey, headerName = 'X-API-Key') {
return { [headerName]: apiKey };
}
// JWT Token认证
createJWTAuth(token) {
return `Bearer ${token}`;
}
// 自定义认证方案
createCustomAuth(scheme, credentials) {
return `${scheme} ${credentials}`;
}
// 解析认证头
parseAuthHeader(authHeader) {
if (!authHeader) return null;
const [scheme, credentials] = authHeader.split(' ', 2);
switch (scheme.toLowerCase()) {
case 'basic':
try {
const decoded = atob(credentials);
const [username, password] = decoded.split(':', 2);
return { scheme: 'Basic', username, password };
} catch (error) {
return { scheme: 'Basic', error: 'Invalid credentials' };
}
case 'bearer':
return { scheme: 'Bearer', token: credentials };
default:
return { scheme, credentials };
}
}
// 验证认证头格式
validateAuthHeader(authHeader) {
if (!authHeader) {
return { valid: false, error: '缺少认证头' };
}
const parts = authHeader.split(' ');
if (parts.length !== 2) {
return { valid: false, error: '认证头格式错误' };
}
const [scheme, credentials] = parts;
if (!scheme || !credentials) {
return { valid: false, error: '认证方案或凭据缺失' };
}
// 验证特定方案
switch (scheme.toLowerCase()) {
case 'basic':
try {
atob(credentials);
return { valid: true, scheme: 'Basic' };
} catch (error) {
return { valid: false, error: 'Basic认证凭据格式错误' };
}
case 'bearer':
if (credentials.length < 10) {
return { valid: false, error: 'Bearer token过短' };
}
return { valid: true, scheme: 'Bearer' };
default:
return { valid: true, scheme };
}
}
}
// 演示认证头部
const authManager = new AuthenticationHeaderManager();
// 创建不同类型的认证头
const basicAuth = authManager.createBasicAuth('user', 'password');
const bearerAuth = authManager.createBearerAuth('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');
const apiKeyAuth = authManager.createApiKeyAuth('abc123456');
console.log('Basic认证:', basicAuth);
console.log('Bearer认证:', bearerAuth);
console.log('API Key认证:', apiKeyAuth);
// 解析认证头
const parsedBasic = authManager.parseAuthHeader(basicAuth);
const parsedBearer = authManager.parseAuthHeader(bearerAuth);
console.log('解析Basic认证:', parsedBasic);
console.log('解析Bearer认证:', parsedBearer);
// 验证认证头
const validationResults = [
authManager.validateAuthHeader(basicAuth),
authManager.validateAuthHeader(bearerAuth),
authManager.validateAuthHeader('Invalid Header'),
authManager.validateAuthHeader('')
];
console.log('认证头验证结果:', validationResults);
}
}
// 创建请求头演示实例
const requestHeadersDemo = new RequestHeadersDemo();响应头用于向客户端传递服务器信息和响应元数据:
// 🎉 HTTP响应头详解
class ResponseHeadersDemo {
constructor() {
this.explainCommonResponseHeaders();
this.demonstrateCacheHeaders();
this.showSecurityHeaders();
}
explainCommonResponseHeaders() {
console.log('=== 常用响应头详解 ===');
const commonResponseHeaders = {
'Content-Type': {
description: '响应体的内容类型',
example: 'Content-Type: application/json; charset=utf-8',
importance: 'critical',
notes: '客户端根据此头部解析响应体'
},
'Content-Length': {
description: '响应体的字节长度',
example: 'Content-Length: 1234',
importance: 'important',
notes: '用于确定响应体边界'
},
'Cache-Control': {
description: '缓存控制指令',
example: 'Cache-Control: max-age=3600, public',
importance: 'critical',
notes: '控制响应的缓存行为'
},
'ETag': {
description: '实体标签,用于缓存验证',
example: 'ETag: "abc123"',
importance: 'important',
notes: '支持条件请求和缓存验证'
},
'Last-Modified': {
description: '资源最后修改时间',
example: 'Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT',
importance: 'important',
notes: '用于条件请求和缓存验证'
},
'Location': {
description: '重定向目标URL',
example: 'Location: https://example.com/new-page',
importance: 'critical',
notes: '用于3xx重定向响应'
},
'Set-Cookie': {
description: '设置客户端Cookie',
example: 'Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure',
importance: 'important',
notes: '可以有多个Set-Cookie头'
},
'Server': {
description: '服务器软件信息',
example: 'Server: nginx/1.18.0',
importance: 'optional',
notes: '可能泄露服务器信息'
},
'Date': {
description: '响应生成时间',
example: 'Date: Wed, 21 Oct 2015 07:28:00 GMT',
importance: 'important',
notes: '用于缓存计算和调试'
},
'Expires': {
description: '响应过期时间',
example: 'Expires: Wed, 21 Oct 2015 07:28:00 GMT',
importance: 'important',
notes: 'HTTP/1.0缓存控制,被Cache-Control替代'
}
};
Object.entries(commonResponseHeaders).forEach(([header, info]) => {
console.log(`${header} (${info.importance}):`);
console.log(` 描述: ${info.description}`);
console.log(` 示例: ${info.example}`);
console.log(` 说明: ${info.notes}`);
console.log('');
});
}
demonstrateCacheHeaders() {
console.log('=== 缓存头部演示 ===');
// 缓存头部管理器
class CacheHeaderManager {
// 创建Cache-Control头
createCacheControl(directives) {
const parts = [];
Object.entries(directives).forEach(([key, value]) => {
if (value === true) {
parts.push(key);
} else if (value !== false) {
parts.push(`${key}=${value}`);
}
});
return parts.join(', ');
}
// 创建ETag头
createETag(content, weak = false) {
// 简单的ETag生成(实际应用中应使用更复杂的算法)
const hash = this.simpleHash(content);
return weak ? `W/"${hash}"` : `"${hash}"`;
}
// 创建Last-Modified头
createLastModified(date) {
return date.toUTCString();
}
// 创建Expires头
createExpires(date) {
return date.toUTCString();
}
// 解析Cache-Control头
parseCacheControl(cacheControlHeader) {
const directives = {};
if (!cacheControlHeader) return directives;
const parts = cacheControlHeader.split(',');
parts.forEach(part => {
const trimmed = part.trim();
const [key, value] = trimmed.split('=');
if (value) {
directives[key] = isNaN(value) ? value : parseInt(value);
} else {
directives[key] = true;
}
});
return directives;
}
// 检查缓存是否有效
isCacheValid(cacheHeaders, requestHeaders) {
const now = new Date();
// 检查Expires
if (cacheHeaders.expires) {
const expiresDate = new Date(cacheHeaders.expires);
if (now > expiresDate) {
return { valid: false, reason: 'Expired by Expires header' };
}
}
// 检查Cache-Control max-age
if (cacheHeaders.cacheControl && cacheHeaders.cacheControl['max-age']) {
const maxAge = cacheHeaders.cacheControl['max-age'];
const responseDate = new Date(cacheHeaders.date || now);
const ageInSeconds = (now - responseDate) / 1000;
if (ageInSeconds > maxAge) {
return { valid: false, reason: 'Expired by max-age' };
}
}
// 检查no-cache指令
if (cacheHeaders.cacheControl && cacheHeaders.cacheControl['no-cache']) {
return { valid: false, reason: 'no-cache directive' };
}
// 检查ETag
if (cacheHeaders.etag && requestHeaders['if-none-match']) {
if (cacheHeaders.etag === requestHeaders['if-none-match']) {
return { valid: true, reason: 'ETag match', status: 304 };
}
}
// 检查Last-Modified
if (cacheHeaders.lastModified && requestHeaders['if-modified-since']) {
const lastModified = new Date(cacheHeaders.lastModified);
const ifModifiedSince = new Date(requestHeaders['if-modified-since']);
if (lastModified <= ifModifiedSince) {
return { valid: true, reason: 'Not modified', status: 304 };
}
}
return { valid: true, reason: 'Cache is valid' };
}
// 简单哈希函数
simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // 转换为32位整数
}
return Math.abs(hash).toString(16);
}
}
// 演示缓存头部
const cacheManager = new CacheHeaderManager();
// 创建不同类型的缓存头
const cacheControlPublic = cacheManager.createCacheControl({
'max-age': 3600,
'public': true
});
const cacheControlPrivate = cacheManager.createCacheControl({
'max-age': 1800,
'private': true,
'no-cache': false
});
const cacheControlNoCache = cacheManager.createCacheControl({
'no-cache': true,
'no-store': true,
'must-revalidate': true
});
console.log('公共缓存:', cacheControlPublic);
console.log('私有缓存:', cacheControlPrivate);
console.log('禁用缓存:', cacheControlNoCache);
// 创建ETag和Last-Modified
const content = 'Hello, World!';
const etag = cacheManager.createETag(content);
const weakETag = cacheManager.createETag(content, true);
const lastModified = cacheManager.createLastModified(new Date());
console.log('强ETag:', etag);
console.log('弱ETag:', weakETag);
console.log('最后修改时间:', lastModified);
// 解析Cache-Control
const parsedCacheControl = cacheManager.parseCacheControl(cacheControlPublic);
console.log('解析的Cache-Control:', parsedCacheControl);
// 检查缓存有效性
const cacheHeaders = {
cacheControl: parsedCacheControl,
etag: etag,
lastModified: lastModified,
date: new Date().toUTCString()
};
const requestHeaders = {
'if-none-match': etag,
'if-modified-since': lastModified
};
const cacheValidation = cacheManager.isCacheValid(cacheHeaders, requestHeaders);
console.log('缓存验证结果:', cacheValidation);
}
showSecurityHeaders() {
console.log('=== 安全头部演示 ===');
const securityHeaders = {
'Strict-Transport-Security': {
description: 'HTTP严格传输安全',
example: 'Strict-Transport-Security: max-age=31536000; includeSubDomains',
purpose: '强制使用HTTPS连接'
},
'Content-Security-Policy': {
description: '内容安全策略',
example: "Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'",
purpose: '防止XSS攻击'
},
'X-Frame-Options': {
description: '框架选项',
example: 'X-Frame-Options: DENY',
purpose: '防止点击劫持攻击'
},
'X-Content-Type-Options': {
description: '内容类型选项',
example: 'X-Content-Type-Options: nosniff',
purpose: '防止MIME类型嗅探'
},
'X-XSS-Protection': {
description: 'XSS保护',
example: 'X-XSS-Protection: 1; mode=block',
purpose: '启用浏览器XSS过滤器'
},
'Referrer-Policy': {
description: '引用策略',
example: 'Referrer-Policy: strict-origin-when-cross-origin',
purpose: '控制Referer头的发送'
},
'Access-Control-Allow-Origin': {
description: 'CORS允许源',
example: 'Access-Control-Allow-Origin: https://example.com',
purpose: '控制跨域访问'
},
'Access-Control-Allow-Methods': {
description: 'CORS允许方法',
example: 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE',
purpose: '指定允许的HTTP方法'
},
'Access-Control-Allow-Headers': {
description: 'CORS允许头部',
example: 'Access-Control-Allow-Headers: Content-Type, Authorization',
purpose: '指定允许的请求头'
}
};
Object.entries(securityHeaders).forEach(([header, info]) => {
console.log(`${header}:`);
console.log(` 描述: ${info.description}`);
console.log(` 示例: ${info.example}`);
console.log(` 用途: ${info.purpose}`);
console.log('');
});
// 安全头部生成器
class SecurityHeaderGenerator {
// 生成基本安全头部
generateBasicSecurityHeaders() {
return {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Referrer-Policy': 'strict-origin-when-cross-origin'
};
}
// 生成HTTPS安全头部
generateHTTPSSecurityHeaders(maxAge = 31536000, includeSubDomains = true) {
const hsts = `max-age=${maxAge}${includeSubDomains ? '; includeSubDomains' : ''}`;
return {
'Strict-Transport-Security': hsts
};
}
// 生成CSP头部
generateCSPHeader(policy) {
const directives = [];
Object.entries(policy).forEach(([directive, sources]) => {
if (Array.isArray(sources)) {
directives.push(`${directive} ${sources.join(' ')}`);
} else {
directives.push(`${directive} ${sources}`);
}
});
return {
'Content-Security-Policy': directives.join('; ')
};
}
// 生成CORS头部
generateCORSHeaders(options) {
const headers = {};
if (options.origin) {
headers['Access-Control-Allow-Origin'] = options.origin;
}
if (options.methods) {
headers['Access-Control-Allow-Methods'] = options.methods.join(', ');
}
if (options.headers) {
headers['Access-Control-Allow-Headers'] = options.headers.join(', ');
}
if (options.credentials) {
headers['Access-Control-Allow-Credentials'] = 'true';
}
if (options.maxAge) {
headers['Access-Control-Max-Age'] = options.maxAge.toString();
}
return headers;
}
}
// 演示安全头部生成
const securityGenerator = new SecurityHeaderGenerator();
const basicSecurity = securityGenerator.generateBasicSecurityHeaders();
console.log('基本安全头部:', basicSecurity);
const httpsSecurity = securityGenerator.generateHTTPSSecurityHeaders();
console.log('HTTPS安全头部:', httpsSecurity);
const cspPolicy = {
'default-src': ["'self'"],
'script-src': ["'self'", "'unsafe-inline'", 'https://cdn.example.com'],
'style-src': ["'self'", "'unsafe-inline'"],
'img-src': ["'self'", 'data:', 'https:']
};
const cspHeaders = securityGenerator.generateCSPHeader(cspPolicy);
console.log('CSP头部:', cspHeaders);
const corsOptions = {
origin: 'https://example.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
headers: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 86400
};
const corsHeaders = securityGenerator.generateCORSHeaders(corsOptions);
console.log('CORS头部:', corsHeaders);
}
}
// 创建响应头演示实例
const responseHeadersDemo = new ResponseHeadersDemo();💼 最佳实践:合理使用HTTP头部可以显著提升Web应用的功能性、安全性和性能,建议建立统一的头部管理策略
通过本节HTTP头部详解的学习,你已经掌握:
A: Content-Type描述发送的内容类型,Accept描述可接受的内容类型。Content-Type用于请求体和响应体,Accept用于内容协商。
A: 根据需求设置Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers等头部,注意安全性和具体性。
A: ETag更精确,支持强弱验证,适合内容频繁变化的场景;Last-Modified基于时间,适合文件系统资源。建议同时使用。
A: 使用HttpOnly防止XSS,Secure确保HTTPS传输,SameSite防止CSRF,设置合适的Path和Domain范围。
A: 传统上使用X-前缀,但RFC 6648不推荐。建议使用描述性名称,避免与标准头部冲突,考虑使用公司或项目前缀。
// 问题:HTTP头部过大导致请求失败
// 解决:优化头部大小和结构
class HeaderSizeOptimizer {
// 检查头部大小
checkHeaderSize(headers) {
const headerString = Object.entries(headers)
.map(([key, value]) => `${key}: ${value}`)
.join('\r\n');
const sizeInBytes = new TextEncoder().encode(headerString).length;
const maxSize = 8192; // 8KB,常见的服务器限制
return {
size: sizeInBytes,
maxSize,
withinLimit: sizeInBytes <= maxSize,
usage: (sizeInBytes / maxSize * 100).toFixed(2) + '%'
};
}
// 优化头部大小
optimizeHeaders(headers) {
const optimized = {};
Object.entries(headers).forEach(([key, value]) => {
// 移除不必要的空格
const trimmedValue = value.trim();
// 压缩某些头部值
if (key.toLowerCase() === 'user-agent') {
// 简化User-Agent
optimized[key] = this.simplifyUserAgent(trimmedValue);
} else {
optimized[key] = trimmedValue;
}
});
return optimized;
}
simplifyUserAgent(userAgent) {
// 保留关键信息,移除详细版本号
return userAgent.replace(/\s+\([^)]+\)/g, '').trim();
}
}// 问题:头部值包含非ASCII字符
// 解决:正确编码头部值
class HeaderEncodingHandler {
// 编码头部值
encodeHeaderValue(value) {
// 检查是否包含非ASCII字符
if (/[^\x00-\x7F]/.test(value)) {
// 使用RFC 2047编码
return this.rfc2047Encode(value);
}
return value;
}
// RFC 2047编码
rfc2047Encode(text, charset = 'utf-8') {
const encoded = Buffer.from(text, charset).toString('base64');
return `=?${charset}?B?${encoded}?=`;
}
// 解码头部值
decodeHeaderValue(value) {
// 检查是否为RFC 2047编码
const rfc2047Pattern = /=\?([^?]+)\?([BQ])\?([^?]+)\?=/gi;
return value.replace(rfc2047Pattern, (match, charset, encoding, encoded) => {
if (encoding.toUpperCase() === 'B') {
// Base64解码
return Buffer.from(encoded, 'base64').toString(charset);
} else if (encoding.toUpperCase() === 'Q') {
// Quoted-Printable解码
return this.quotedPrintableDecode(encoded);
}
return match;
});
}
quotedPrintableDecode(encoded) {
return encoded
.replace(/_/g, ' ')
.replace(/=([0-9A-F]{2})/gi, (match, hex) => {
return String.fromCharCode(parseInt(hex, 16));
});
}
}"掌握HTTP头部是Web开发的重要技能,通过合理使用各种头部字段,你将能够构建更加功能完善、安全可靠和性能优异的Web应用!"