在 AJAX 请求中设置 HTTP 头部(Header)是一项重要技能,可以帮助你传递认证信息、控制缓存、指定内容类型等。本指南将详细介绍如何在不同的 JavaScript 环境中设置 AJAX 请求的 Header。
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
// 设置单个 Header
xhr.setRequestHeader('Content-Type', 'application/json');
// 设置多个 Header
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader('X-Custom-Header', 'CustomValue');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
function makeXHRRequest(method, url, data, headers) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
// 设置所有提供的 Header
if (headers) {
Object.keys(headers).forEach(key => {
xhr.setRequestHeader(key, headers[key]);
});
}
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = function() {
reject(new Error('Network Error'));
};
xhr.send(data);
});
}
// 使用示例
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer abc123',
'X-Requested-With': 'XMLHttpRequest'
};
makeXHRRequest('POST', '/api/data', JSON.stringify({name: 'John'}), headers)
.then(response => console.log(response))
.catch(error => console.error(error));
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer ' + token);
fetch('https://api.example.com/data', {
method: 'GET',
headers: headers
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
'X-Custom-Header': 'CustomValue'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data));
async function fetchWithHeaders(url, options = {}) {
const defaultHeaders = {
'Content-Type': 'application/json',
};
const headers = {
...defaultHeaders,
...options.headers
};
const config = {
...options,
headers
};
try {
const response = await fetch(url, config);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// 检查响应内容类型
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return await response.json();
}
return await response.text();
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}
// 使用示例
const customHeaders = {
'Authorization': 'Bearer abc123',
'X-API-Key': 'your-api-key-here'
};
fetchWithHeaders('https://api.example.com/data', {
method: 'POST',
headers: customHeaders,
body: JSON.stringify({ name: 'John' })
})
.then(data => console.log(data))
.catch(error => console.error(error));
$.ajax({
url: 'https://api.example.com/data',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
data: JSON.stringify({ name: 'John' }),
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
// 设置全局 Header(所有 AJAX 请求都会包含)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'X-Requested-With': 'XMLHttpRequest'
}
});
$.ajax({
url: '/api/data',
type: 'GET',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
},
success: function(data) {
console.log(data);
}
});
import axios from 'axios';
// 实例配置
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
});
// 请求时设置 Header
instance.get('/data', {
headers: {
'Authorization': 'Bearer ' + token
}
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
// 设置全局 Header
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
axios.defaults.headers.post['Content-Type'] = 'application/json';
// 或者为特定请求方法设置默认 Header
axios.defaults.headers.get['Accept'] = 'application/json';
// 请求拦截器 - 在发送请求前添加 Header
axios.interceptors.request.use(
config => {
// 从 localStorage 获取 token
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);
// 响应拦截器 - 处理响应
axios.interceptors.response.use(
response => response,
error => {
if (error.response && error.response.status === 401) {
// 处理未授权错误
console.log('Token expired, redirecting to login');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
// Bearer Token (JWT)
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...'
}
// Basic 认证
headers: {
'Authorization': 'Basic ' + btoa(username + ':' + password)
}
// API Key
headers: {
'X-API-Key': 'your-api-key-here'
}
// JSON 数据
headers: {
'Content-Type': 'application/json'
}
// 表单数据
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
// 文件上传
headers: {
'Content-Type': 'multipart/form-data'
}
// XML 数据
headers: {
'Content-Type': 'application/xml'
}
// CORS 相关
headers: {
'Origin': 'https://yourdomain.com'
}
// 缓存控制
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
}
// CSRF 保护
headers: {
'X-CSRF-Token': 'token-from-meta-tag'
}
// 标识请求来源
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
// 语言/地区偏好
headers: {
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
}
class ApiService {
constructor(baseURL) {
this.baseURL = baseURL;
this.token = localStorage.getItem('auth_token');
}
// 获取默认 Header
getDefaultHeaders() {
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`;
}
return headers;
}
// 通用请求方法
async request(endpoint, method = 'GET', data = null, customHeaders = {}) {
const url = `${this.baseURL}${endpoint}`;
const headers = {
...this.getDefaultHeaders(),
...customHeaders
};
const config = {
method,
headers,
credentials: 'include' // 如果需要发送 cookies
};
if (data) {
if (headers['Content-Type'] === 'application/json') {
config.body = JSON.stringify(data);
} else if (headers['Content-Type'] === 'application/x-www-form-urlencoded') {
config.body = new URLSearchParams(data);
} else {
config.body = data;
}
}
try {
const response = await fetch(url, config);
// 处理不同的响应状态
if (!response.ok) {
if (response.status === 401) {
// Token 过期,刷新或重定向到登录
this.handleUnauthorized();
throw new Error('Authentication required');
}
if (response.status === 403) {
throw new Error('Permission denied');
}
throw new Error(`Request failed with status ${response.status}`);
}
// 根据响应内容类型解析响应
const contentType = response.headers.get('content-type');
let result;
if (contentType && contentType.includes('application/json')) {
result = await response.json();
} else {
result = await response.text();
}
return result;
} catch (error) {
console.error('API Request Error:', error);
throw error;
}
}
// 具体 API 方法
async login(credentials) {
return this.request('/auth/login', 'POST', credentials);
}
async getUserProfile() {
return this.request('/user/profile', 'GET');
}
async updateUserProfile(profileData) {
return this.request('/user/profile', 'PUT', profileData);
}
async uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
return this.request('/upload', 'POST', formData, {
'Content-Type': 'multipart/form-data'
});
}
handleUnauthorized() {
// 清除 token 并重定向到登录页
localStorage.removeItem('auth_token');
window.location.href = '/login';
}
}
// 使用示例
const api = new ApiService('https://api.example.com');
// 登录
api.login({ username: 'user', password: 'pass' })
.then(data => {
localStorage.setItem('auth_token', data.token);
api.token = data.token;
})
.then(() => api.getUserProfile())
.then(profile => console.log(profile))
.catch(error => console.error(error));
async function uploadFile(file, uploadUrl, progressCallback) {
const formData = new FormData();
formData.append('file', file);
formData.append('uploadedAt', new Date().toISOString());
const xhr = new XMLHttpRequest();
// 设置上传进度监听
if (progressCallback) {
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
progressCallback(percentComplete);
}
});
}
return new Promise((resolve, reject) => {
xhr.open('POST', uploadUrl);
// 设置文件上传相关 Header
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
xhr.setRequestHeader('X-File-Size', file.size);
xhr.setRequestHeader('X-File-Type', file.type);
xhr.setRequestHeader('X-File-Name', encodeURIComponent(file.name));
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error(`Upload failed: ${xhr.statusText}`));
}
};
xhr.onerror = () => reject(new Error('Network error'));
xhr.send(formData);
});
}
// 服务器需要正确设置 CORS Header
headers: {
'Access-Control-Allow-Origin': 'https://yourdomain.com',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': 'true'
}
// 使用浏览器开发者工具查看请求 Header
// 1. 打开 Network 面板
// 2. 找到对应的请求
// 3. 查看 Request Headers 部分
// 在代码中调试 Header
console.log('Request headers:', headers);
// 使用代理工具
// - Charles Proxy
// - Fiddler
// - Wireshark
// 错误:设置 Header 时机不正确
// 必须在 open() 之后,send() 之前设置 Header
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.setRequestHeader('Content-Type', 'application/json'); // 正确位置
xhr.send();
// 错误:部分 Header 无法通过 JavaScript 设置
// 以下 Header 由浏览器控制,无法手动设置:
// - Host
// - Connection
// - Content-Length
// - Cache-Control (部分限制)
// - 等等
// 错误:Content-Type 与数据格式不匹配
// 发送 JSON 数据但忘记设置 Content-Type
fetch('/api/data', {
method: 'POST',
body: JSON.stringify(data) // 需要设置 'Content-Type': 'application/json'
});
通过本指南,你应该能够熟练掌握在不同 JavaScript 环境中设置 AJAX 请求 Header 的方法。根据你的项目需求和技术栈,选择合适的方法来实现 HTTP 请求的 Header 设置。