iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0
自我挑戰組

利用30分鐘~想一個前端問題系列 第 27

利用30分鐘~想一個前端問題 Day27-httpGet

httpGet

Makes a GET request to the passed URL.

Use XMLHttpRequest web api to make a get request to the given url.
Handle the onload event, by calling the given callback the responseText.
Handle the onerror event, by running the provided err function.
Omit the third argument, err, to log errors to the console's error stream by default.

對傳遞的URL進行GET請求。

使用XMLHttpRequest Web API對給定的URL進行get請求。

通過監聽onload事件呼叫 responseText。

通過 提過錯誤function 發生 onerror 事件

通過 err函數來處理on error事件。 省略第三個參數err,錯誤的log放到console.log裡


const httpGet = (url, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send();
};
//EXAMPLES
httpGet(
  'https://jsonplaceholder.typicode.com/posts/1',
  console.log
); /*
Logs: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
*/

分析點

1.new XMLHttpRequest()

XMLHttpRequest (XHR), 是最常見的 JavaScript HTTP Client,
常見於 Web 應用、Debug、API 測試…
頁面 能透過它操作 HTTP 請求,進行網路作業,
擷取資料的同時,卻 不需 進行 頁面重載 (page reload)

執行順序如下:

根據 MDN 提供的描述,要送出一個 HTTP 請求,需要三個步驟:

  • 建立一個 XMLHttpRequest 物件
  • 開啟一個 URL
  • 發送一個請求

建立一個XMLHttpRequest 物件
const request = new XMLHttpRequest();

開啟一個 URL

開啟對伺服端的連結;method 為 HTTP 請求方式('GET'、'POST'、'HEAD' 等);url 為伺服端位址,如果是 GET 的話,可加上請求參數與值;asynch 為非同步設定,預設是 true,表示使用非同步方式,username、password 視伺服端有無要求驗證而設置。

request.open('GET', url, true);

監聽事件


request.onload = () => callback(request.responseText);

XMLHttpRequest 物件將會包含如回應內容(response body)及 HTTP 狀態等等請求結果中的有用資訊。

發送請求

對伺服端傳送請求,open 的 method 為 'GET' 時,content 設為 null,'POST' 時 content 可放字串、XML、JSON 格式的內容,會放在 POST 本體中發送。在早期,瀏覽器不一定支援全部的 HTTP 方法。

request.responseText

回應的文字 text,能透過 responseText 屬性 取得,
若回應的是 常見的 JSON,則可以使用 JSON.parse() 方法,解析 responseText 屬性。

2.console.err

把錯誤的訊息放在 console.log 上面,常用在開發上面

參考文章

MDN 使用 XMLHttpRequest

輕鬆理解 Ajax 與跨來源請求


上一篇
利用30分鐘~想一個前端問題 Day26-randomHexColorCode
下一篇
利用30分鐘~想一個前端問題 Day28-chainAsync
系列文
利用30分鐘~想一個前端問題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言