前端JavaScript 6 种主流接口请求技术全解
作者:秋水为渡
这篇文章主要介绍了前端JavaScript 6 种主流接口请求技术的相关资料,包括XMLHttpRequest、FetchAPI、Axios、jQueryAjax、WebSocket和GraphQL,并提供了每种方案的基础用法、高级配置、优点、缺点及适用场景,文中通过代码介绍的非常详细,需要的朋友可以参考下
本文全面讲解 6 种主流接口请求方案,涵盖原生 API 与流行库实现,提供可直接复用的代码模板与最佳实践指南。
一、XMLHttpRequest(原生方案)
1.1 基础使用
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.error('请求失败:', xhr.statusText);
  }
};
xhr.onerror = function() {
  console.error('网络错误');
};
xhr.send();
1.2 高级配置
// POST 请求示例
xhr.open('POST', 'https://api.example.com/submit');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ name: 'John', age: 25 }));
// 超时控制
xhr.timeout = 5000;
xhr.ontimeout = function() {
  console.error('请求超时');
};
优点:
- 浏览器原生支持
 - 精细控制请求过程
 
缺点:
- 回调地狱问题
 - 需手动处理响应解析
 - 缺乏 Promise 支持
 
二、Fetch API(现代标准)
2.1 基础请求
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('请求失败:', error));
2.2 高级配置
// POST 请求配置
fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  },
  body: JSON.stringify({ title: 'New Post' }),
  credentials: 'include', // 携带 cookies
  mode: 'cors' // 跨域模式
});
// 取消请求
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
fetch(url, { signal: controller.signal })
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('请求被取消');
    }
  });
优势:
- Promise 链式调用
 - 内置响应解析方法
 - 支持流式数据处理
 
局限:
- 默认不携带 cookies
 - 错误处理需要额外判断
 - 不支持超时直接配置
 
三、Axios(流行库)
3.1 基础用法
import axios from 'axios';
// GET 请求
axios.get('/user?ID=12345')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
// POST 请求
axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
}, {
  headers: { 'X-Custom-Header': 'value' }
});
3.2 全局配置
// 创建实例
const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
// 请求拦截
api.interceptors.request.use(config => {
  config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
  return config;
});
// 响应拦截
api.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response?.status === 401) {
      window.location = '/login';
    }
    return Promise.reject(error);
  }
);
核心特性:
- 自动转换 JSON 数据
 - 客户端 XSRF 防护
 - 并发请求处理
 - 请求取消支持
 
四、jQuery Ajax(传统方案)
4.1 基础实现
$.ajax({
  url: 'https://api.example.com/data',
  method: 'GET',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(xhr, status, error) {
    console.error(error);
  }
});
4.2 全局配置
// 设置默认参数
$.ajaxSetup({
  timeout: 3000,
  headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
// 使用 Promise
$.getJSON('https://api.example.com/items')
  .done(data => console.log(data))
  .fail((jqXHR, textStatus, errorThrown) => {
    console.error(textStatus, errorThrown);
  });
适用场景:
- 老项目维护
 - 需要兼容 IE9 等旧浏览器
 
五、WebSocket(实时通信)
5.1 基础实现
const socket = new WebSocket('wss://api.example.com/ws');
socket.onopen = function() {
  console.log('连接已建立');
  socket.send(JSON.stringify({ action: 'subscribe', channel: 'updates' }));
};
socket.onmessage = function(event) {
  const data = JSON.parse(event.data);
  console.log('收到消息:', data);
};
socket.onclose = function(event) {
  console.log('连接关闭:', event.code, event.reason);
};
5.2 断线重连
let socket;
function connect() {
  socket = new WebSocket(url);
  
  socket.onclose = function() {
    setTimeout(connect, 5000);
  };
}
connect();
最佳实践:
- 使用心跳包保持连接
 - 实现消息队列重发机制
 - 使用 STOMP 等协议封装
 
六、GraphQL 请求
6.1 使用 Fetch 实现
fetch('/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    query: `
      query GetUser($id: ID!) {
        user(id: $id) {
          name
          email
        }
      }
    `,
    variables: { id: '123' }
  })
})
.then(res => res.json())
.then(data => console.log(data.data.user));
6.2 使用 Apollo Client
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
  uri: '/graphql',
  cache: new InMemoryCache()
});
client.query({
  query: gql`
    query GetBooks {
      books {
        title
        author
      }
    }
  `
}).then(result => console.log(result.data));
七、综合对比与选型指南
| 方案 | 适用场景 | 优点 | 缺点 | 
|---|---|---|---|
| XMLHttpRequest | 需要精细控制的老旧项目 | 无需额外依赖 | 代码冗长,回调地狱 | 
| Fetch API | 现代浏览器项目 | 原生支持,简洁语法 | 需手动处理错误和超时 | 
| Axios | 复杂企业级应用 | 功能全面,拦截器机制 | 增加包体积 | 
| jQuery Ajax | 维护旧 jQuery 项目 | 简化异步操作 | 依赖 jQuery,已过时 | 
| WebSocket | 实时通信需求 | 双向实时通信 | 实现复杂度高 | 
| GraphQL | 复杂数据查询场景 | 精确获取数据,减少请求次数 | 学习曲线陡峭 | 
八、最佳实践与安全防护
8.1 通用安全策略
// CSRF 防护
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
// 请求签名
function signRequest(config) {
  const timestamp = Date.now();
  const signature = crypto.createHmac('sha256', SECRET)
    .update(`${config.url}${timestamp}`)
    .digest('hex');
    
  config.headers['X-Signature'] = signature;
  config.headers['X-Timestamp'] = timestamp;
  return config;
}
8.2 性能优化方案
// 请求缓存
const cache = new Map();
async function cachedFetch(url) {
  if (cache.has(url)) {
    return cache.get(url);
  }
  
  const response = await fetch(url);
  const data = await response.json();
  cache.set(url, data);
  return data;
}
// 请求合并
let pendingRequests = {};
function batchRequest(url) {
  if (!pendingRequests[url]) {
    pendingRequests[url] = fetch(url).then(res => res.json());
  }
  return pendingRequests[url];
}
九、错误处理标准范式
9.1 统一错误处理
// Axios 错误分类
function handleError(error) {
  if (error.response) {
    // 服务器响应异常 (2xx 外的状态码)
    console.error('Server Error:', error.response.status);
  } else if (error.request) {
    // 请求已发出但无响应
    console.error('Network Error:', error.message);
  } else {
    // 请求配置错误
    console.error('Config Error:', error.message);
  }
}
9.2 重试机制实现
function fetchWithRetry(url, retries = 3) {
  return new Promise((resolve, reject) => {
    const attempt = (remaining) => {
      fetch(url)
        .then(resolve)
        .catch(error => {
          if (remaining > 0) {
            console.log(`剩余重试次数: ${remaining}`);
            attempt(remaining - 1);
          } else {
            reject(error);
          }
        });
    };
    attempt(retries);
  });
}
十、TypeScript 类型增强
10.1 Axios 响应类型
interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}
const api = axios.create({
  baseURL: '/api',
  responseType: 'json'
});
api.interceptors.response.use(
  (response): ApiResponse<unknown> => {
    if (response.data.code !== 200) {
      throw new Error(response.data.message);
    }
    return response.data;
  }
);
// 使用泛型请求
function getUser<T>(id: string) {
  return api.get<ApiResponse<T>>(`/users/${id}`);
}
总结与扩展方向
扩展学习建议:
- 掌握 HTTP/2 服务器推送技术
 - 研究 WebTransport 新协议
 - 学习 Service Worker 离线缓存
 - 探索 WebRTC 点对点通信
 
版本兼容方案:
// 动态加载 polyfill
if (!window.fetch) {
  import('whatwg-fetch').then(() => {
    console.log('Fetch polyfill loaded');
  });
}
根据项目需求灵活选择请求方案,现代项目推荐优先使用 Fetch API 或 Axios。始终遵循安全最佳实践,在性能与功能需求间寻找平衡点。
到此这篇关于前端JavaScript 6 种主流接口请求技术的文章就介绍到这了,更多相关JS接口请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
