JavaScript发送HTTP请求的主要方法详解
作者:detayun
在Web开发中,JavaScript与服务器进行数据交互是核心需求之一,本文详细介绍了JavaScript中发送HTTP请求的几种主要方法,大家可以根据需要进行选择
在Web开发中,JavaScript与服务器进行数据交互是核心需求之一。从早期的原生AJAX到现代Fetch API,再到第三方库如Axios,前端请求方案不断迭代优化。本文将详细解析JavaScript发送请求的常用方法,帮助开发者根据场景选择最适合的方案。
一、原生AJAX(XMLHttpRequest)
1. 基础用法
XMLHttpRequest(XHR)是浏览器原生支持的异步请求技术,通过创建对象并配置请求参数实现数据交互:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true); // 异步请求
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
2. POST请求示例
发送JSON数据时需设置请求头并序列化参数:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/submit', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 201) console.log('创建成功');
else console.error('请求失败:', xhr.statusText);
}
};
xhr.send(JSON.stringify({ name: 'Alice', age: 25 }));
3. 优缺点分析
优点:兼容性好(IE6+支持),可监听上传进度(upload.onprogress)
缺点:
- 代码冗长,需手动管理状态
- 默认不携带Cookie(需设置
xhr.withCredentials = true) - 跨域请求需后端配置
Access-Control-Allow-Credentials
二、Fetch API
1. 基础用法
Fetch基于Promise实现更简洁的异步操作:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('Network error');
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
2. POST请求示例
fetch('https://api.example.com/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Bob', age: 30 }),
credentials: 'include' // 携带Cookie
})
.then(response => response.json())
.then(data => console.log(data))
.catch(console.error);
3. 高级特性
超时控制:通过AbortController实现
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
fetch('https://api.example.com/data', { signal: controller.signal })
.catch(err => {
if (err.name === 'AbortError') console.log('请求超时');
});
流式响应:处理大文件时使用response.body.getReader()
4. 优缺点分析
优点:语法简洁,支持流式处理,天然Promise链式调用
缺点:
- 默认不处理404/500等错误状态码(需手动检查
response.ok) - 跨域请求需后端配置
Access-Control-Allow-Origin - 兼容性(IE不支持,需polyfill)
三、第三方库方案
1. Axios
核心特性
- 自动JSON转换
- 请求/响应拦截器
- 取消请求(
CancelToken) - 客户端防御XSRF
示例代码
axios.post('https://api.example.com/submit', { name: 'Charlie' })
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
console.error('服务器错误:', error.response.status);
} else {
console.error('网络错误:', error.message);
}
});
2. jQuery AJAX
传统写法
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json',
success: function(data) { console.log(data); },
error: function(xhr, status, error) { console.error(error); }
});
简写形式
$.get('https://api.example.com/data', function(data) {
console.log(data);
});
四、特殊场景方案
1. 表单模拟提交(PUT/DELETE)
通过隐藏表单实现非GET/POST方法的提交:
function submitWithMethod(url, method, data) {
const form = document.createElement('form');
form.method = 'POST'; // 表单原生不支持PUT/DELETE
form.action = url;
// 添加_method字段模拟真实HTTP方法
const methodInput = document.createElement('input');
methodInput.type = 'hidden';
methodInput.name = '_method';
methodInput.value = method;
form.appendChild(methodInput);
// 添加数据字段
Object.entries(data).forEach(([key, value]) => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = value;
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
}
// 使用示例
submitWithMethod('/orders/123', 'PUT', { status: 'shipped' });
2. 文件上传进度监控
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/upload', true);
// 上传进度事件
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100);
console.log(`上传进度: ${percent}%`);
}
};
xhr.send(new FormData(document.getElementById('uploadForm')));
五、选择建议
| 场景 | 推荐方案 | 理由 |
|---|---|---|
| 现代浏览器开发 | Fetch API | 语法简洁,支持流式处理,与Promise生态无缝集成 |
| 需要兼容IE | Axios | 自动降级处理,提供统一的错误处理机制 |
| 复杂业务逻辑 | Axios拦截器 | 通过拦截器统一处理认证、日志、错误重试等横切关注点 |
| 大文件上传 | XHR | 支持进度监控,可配合分片上传策略 |
| 表单重定向提交 | 隐藏表单法 | 浏览器自动处理Cookie,后端可识别_method字段模拟PUT/DELETE |
六、最佳实践
错误处理:始终检查HTTP状态码,不要依赖catch捕获所有错误
安全防护:
- 敏感操作使用HTTPS
- 跨域请求配置CORS头
- 重要操作添加CSRF Token
性能优化:
- 合理使用缓存(
Cache-Control) - 大文件采用分片上传
- 频繁请求使用WebSocket或Server-Sent Events
调试技巧:
- 使用浏览器Network面板验证请求头/体
- 通过
console.log(response)检查原始响应结构 - 复杂场景使用Postman等工具先验证接口
结语
JavaScript请求方案的选择应基于项目需求、团队熟悉度和浏览器兼容性。现代项目推荐以Fetch API为主,复杂场景引入Axios增强功能,同时保持对XHR的理解以便维护遗留代码。无论采用哪种方案,始终牢记安全性、可维护性和性能这三个核心原则。
到此这篇关于JavaScript发送HTTP请求的主要方法详解的文章就介绍到这了,更多相关JavaScript发送HTTP请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
