每日 30 秒 ⏱ 一個簡單的 HTTP 請求客戶端

簡介

XMLHttpRequest、HTTP 工具原理、XHRjavascript

jQuery.ajax、axios和 新的 Web APIfetch在瀏覽器不支持的兼容代碼都是利用XMLHttpRequest來完成網絡請求,今天一塊兒來實現一個簡單的HTTP 請求客戶端順便學習XMLHttpRequest` 中較爲經常使用的函數方法:java

const http = ({
  url,
  callback,
  data=null,
  method='GET',
  err = console.error,
}) => {
    const request = new XMLHttpRequest();
    request.open(method, url, true);
    request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    request.onerror = () => err(request);
    request.onload = () => callback(request.responseText);
    request.send(data ? JSON.stringify(data) : null);
};
複製代碼

代碼分析

函數爲接受一個對象參數,而不是像 (url, callback) 這樣的參數列表?由於使用對象相對參數列表來講不用刻意的去記參數的順序只須要記住所需數據:ios

小技巧:根據狀況利用對象參數來代替參數列表。git

const http = ({
  url,
  callback,
  data=null,
  method='GET',
  err = console.error,
}) => {
    // ...
};
複製代碼

建立 XMLHttpRequest 對象並使用 XMLHttpRequest.open() 方法初始化一個請求(這裏的 method 能夠是 GET、POST、PUT、DELETE):github

const request = new XMLHttpRequest();
request.open(method, url, true);
複製代碼

設置 Request Header 中的內容類型:ajax

request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
複製代碼

當請求完成時利用 回調函數 來執行外部傳入的代碼:json

小技巧:善用用回調函數。axios

request.onerror = () => err(request);
request.onload = () => callback(request.responseText);
複製代碼

發送須要帶上的數據:api

request.send(data ? JSON.stringify(data) : null);
複製代碼

使用場景

手癢的同窗能夠開始動手加上 Promise 或者按照 axios API 實現一個本身的 HTTP Client,好奇寶寶能夠試試閱讀相關 axiosfetch 源碼。下面給出幾個使用例子:瀏覽器

http({
    method: 'POST',
    url: 'http://pushme.top/api/v1/posts',
    callback: console.log, 
    data: { title: 'hello', content: 'hello world'}
})

http({
    method: 'GET',
    url: 'http://pushme.top/api/v1/posts',
    callback: console.log, 
})
複製代碼

一塊兒成長

在困惑的城市裏總少不了並肩同行的 夥伴 讓咱們一塊兒成長。

  • 若是您想讓更多人看到文章能夠點個 點贊
  • 若是您想激勵小二能夠到 Github 給個 小星星
  • 若是您想與小二更多交流添加微信 m353839115

微信公衆號

本文原稿來自 PushMeTop

相關文章
相關標籤/搜索