最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

前端JavaScript?6?種主流接口請求技術全解

 更新時間:2025年03月11日 09:26:50   作者:秋水為渡  
這篇文章主要介紹了前端JavaScript?6?種主流接口請求技術的相關資料,包括XMLHttpRequest、FetchAPI、Axios、jQueryAjax、WebSocket和GraphQL,并提供了每種方案的基礎用法、高級配置、優(yōu)點、缺點及適用場景,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

本文全面講解 6 種主流接口請求方案,涵蓋原生 API 與流行庫實現(xiàn),提供可直接復用的代碼模板與最佳實踐指南。

一、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('請求超時');
};

優(yōu)點

  • 瀏覽器原生支持
  • 精細控制請求過程

缺點

  • 回調地獄問題
  • 需手動處理響應解析
  • 缺乏 Promise 支持

二、Fetch API(現(xiàn)代標準)

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('請求被取消');
    }
  });

優(yōu)勢

  • 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 全局配置

// 創(chuàng)建實例
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 防護
  • 并發(fā)請求處理
  • 請求取消支持

四、jQuery Ajax(傳統(tǒng)方案)

4.1 基礎實現(xiàn)

$.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 基礎實現(xiàn)

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();

最佳實踐

  • 使用心跳包保持連接
  • 實現(xiàn)消息隊列重發(fā)機制
  • 使用 STOMP 等協(xié)議封裝

六、GraphQL 請求

6.1 使用 Fetch 實現(xiàn)

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));

七、綜合對比與選型指南

方案適用場景優(yōu)點缺點
XMLHttpRequest需要精細控制的老舊項目無需額外依賴代碼冗長,回調地獄
Fetch API現(xiàn)代瀏覽器項目原生支持,簡潔語法需手動處理錯誤和超時
Axios復雜企業(yè)級應用功能全面,攔截器機制增加包體積
jQuery Ajax維護舊 jQuery 項目簡化異步操作依賴 jQuery,已過時
WebSocket實時通信需求雙向實時通信實現(xiàn)復雜度高
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 性能優(yōu)化方案

// 請求緩存
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 統(tǒng)一錯誤處理

// Axios 錯誤分類
function handleError(error) {
  if (error.response) {
    // 服務器響應異常 (2xx 外的狀態(tài)碼)
    console.error('Server Error:', error.response.status);
  } else if (error.request) {
    // 請求已發(fā)出但無響應
    console.error('Network Error:', error.message);
  } else {
    // 請求配置錯誤
    console.error('Config Error:', error.message);
  }
}

9.2 重試機制實現(xiàn)

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 新協(xié)議
  • 學習 Service Worker 離線緩存
  • 探索 WebRTC 點對點通信

版本兼容方案:

// 動態(tài)加載 polyfill
if (!window.fetch) {
  import('whatwg-fetch').then(() => {
    console.log('Fetch polyfill loaded');
  });
}

根據項目需求靈活選擇請求方案,現(xiàn)代項目推薦優(yōu)先使用 Fetch API 或 Axios。始終遵循安全最佳實踐,在性能與功能需求間尋找平衡點。

到此這篇關于前端JavaScript 6 種主流接口請求技術的文章就介紹到這了,更多相關JS接口請求內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

南和县| 清流县| 明光市| 东阳市| 华蓥市| 临江市| 泉州市| 嘉兴市| 项城市| 阳新县| 浙江省| 沾化县| 佳木斯市| 沁阳市| 浦江县| 长丰县| 巨野县| 泰来县| 崇礼县| 沙田区| 台江县| 修水县| 鹿泉市| 宝鸡市| 耒阳市| 二手房| 夏津县| 藁城市| 同仁县| 泌阳县| 互助| 张家界市| 获嘉县| 永平县| 长治县| 天台县| 梧州市| 塔城市| 通辽市| 临安市| 湖南省|