如何使用 JavaScript Fetch API 獲取資料?
如今,JavaScript 可用於編寫前端和後端程式碼。此外,它也是最廣泛使用的程式語言。
此外,在開發即時應用程式時,我們需要從其他伺服器獲取資料。我們可以使用 API(應用程式程式設計介面)從其他伺服器或資料庫獲取資料。
在這裡,我們將學習使用 JavaScript 獲取 API 資料的各種方法。
使用 fetch() 方法
fetch() 是瀏覽器中用於從 API 獲取資料的方法。它將 API URL 作為第一個引數(我們需要獲取資料),並將選項作為第二個引數。選項可以包含標頭和身份驗證令牌。
語法
使用者可以使用以下語法使用 fetch() 獲取資料。
fetch(baseURL)
.then(data => {
// use data here
}
在上述語法中,baseURL 是獲取資料的 API。
示例 1
在下面的示例中,當用戶單擊按鈕時,它將執行 fetchData() 函式。在 fetchData() 函式中,我們使用了 fetch() 方法從 API 獲取資料。之後,我們處理了響應和錯誤。使用者可以在輸出中看到我們從 API 獲取的資料。
<html>
<body>
<h2>Using the <i> fetch() browser method </i> to fetch data from API</h2>
<div id = "output"> </div>
<button onclick = "fetchData()"> Fetch API to get data </button>
<script>
let output = document.getElementById('output');
function fetchData() {
fetch('https://dummyjson.com/products/1')
.then(response => response.json())
.then(data => {
output.innerHTML += "id = " + data.id + "<br/>";
output.innerHTML += "brand = " + data.brand + "<br/>";
output.innerHTML += "category = " + data.category + "<br/>";
output.innerHTML += "price = " + data.price + "<br/>";
output.innerHTML += "rating = " + data.rating + "<br/>";
output.innerHTML += "stock = " + data.stock + "<br/>";
})
}
</script>
</body>
</html>
使用 axios npm 包
axios 是一個 NPM 包,允許開發人員透過發出 GET、POST、PUT 等請求來與 API 互動。在這裡,我們將使用 axios 發出 GET 請求以在 JavaScript 中獲取資料。
語法
使用者可以按照以下語法使用 axios 從 API 獲取資料。
axios.get(URL)
.then((response) => {
// use response
}
在上述語法中,我們使用了 axios.get() 方法從 API 獲取資料。
示例 2
在這個例子中,我們使用 then() 和 catch() 塊解析從伺服器或資料庫獲得的 Promise。我們在 then() 塊中使用了資料,在 catch() 塊中使用了錯誤。
<html>
<head>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"></script>
</head>
<body>
<h2>Using the <i> Axios NPM package </i> to fetch data from API</h2>
<div id = "output"> </div>
<button onclick = "fetchData()"> Fetch data using Axios </button>
<script>
let output = document.getElementById('output');
function fetchData() {
axios.get("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => {
output.innerHTML += "userId : " + response.data.userId + "<br/>";
output.innerHTML += "id : " + response.data.id + "<br/>";
output.innerHTML += "title : " + response.data.title + "<br/>";
output.innerHTML += "completed : " + response.data.completed + "<br/>";
})
.catch((err) => {
output.innerHTML += "The error is - " + err + "<br/>";
})
}
</script>
</body>
</html>
示例 3
在下面的示例中,我們使用了 axios 來使用 async/await 語法獲取資料。我們將 getData() 函式設定為非同步的。此外,我們還在 axios 中使用了 await 關鍵字,以暫停函式的執行,直到我們從 API 獲取響應。
<html>
<head>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"></script>
</head>
<body>
<h2>Using the <i> Axios NPM package </i> with Async/await syntax to fetch data from API</h2>
<div id = "output"> </div>
<button onclick = "getData()"> get data using Axios </button>
<script>
let output = document.getElementById('output');
async function getData() {
let response = await
axios.get("https://jsonplaceholder.typicode.com/todos/1")
for (let key in response.data) {
output.innerHTML += key + " - " + response.data[key] + "<br/>";
}
}
</script>
</body>
</html>
使用 XMLHttpRequest web API
XMLHttpRequest web API 允許我們建立自己的模組來獲取資料。我們可以建立一個物件並使用 XMLHttpRequest 初始化它。之後,我們可以使用該物件開啟一個 GET 請求。
之後,我們可以在 XMLHttpRequest 載入時呼叫回撥函式。回撥函式可以獲取響應狀態並相應地返回響應或錯誤。
語法
const xmlRequest = new XMLHttpRequest();
xmlRequest.open('GET', apiURL);
xmlRequest.responseType = 'json';
xmlRequest.onload = function () {
// handle the response from API
}
xmlRequest.send();
在上述語法中,我們首先使用 open() 方法開啟請求,並使用 onload 事件處理來自 API 的響應。
示例 4
在下面的示例中,我們必須使用 XMLHttpRequest() web API 建立一個自定義模組來從 API 獲取資料。customRequest() 函式包含自定義模組。
之後,我們透過將 URL 作為引數呼叫 customRequest() 函式,並使用 then() 塊解析從 customRequest() 函式返回的 Promise。
<html>
<body>
<h2>Using the <i> XMLHttpRequest web API </i> to fetch data from API</h2>
<div id = "output"> </div>
<button onclick = "getData()"> get data </button>
<script>
let output = document.getElementById('output');
const customRequest = (apiURL) => {
return new Promise((res, rej) => {
// Create a new Object of XMLHttpRequest
const xmlRequest = new XMLHttpRequest();
// open a get request
xmlRequest.open('GET', apiURL);
// set response type
xmlRequest.responseType = 'json';
xmlRequest.onload = function () {
// resolve the promise when we get a successful response
if (xmlRequest.status == 200) {
res(xmlRequest.response);
} else {
// reject promise on error
rej(xmlRequest.response);
}
};
// send request
xmlRequest.send();
});
};
// making the get request from URL
const getData = async () => {
try {
const data = await customRequest(
'https://dummyjson.com/products/1',
);
output.innerHTML += "category = " + data.category + "<br/>";
output.innerHTML += "price = " + data.price + "<br/>";
output.innerHTML += "rating = " + data.rating + "<br/>";
output.innerHTML += "stock = " + data.stock + "<br/>";
} catch (err) {
output.innerHTML += "The error is : " + err + "<br/>";
}
};
</script>
</body>
</html>
我們學習了三種不同的從 API 獲取資料的方法。最好的方法是使用瀏覽器的 fetch() 方法,因為我們不需要安裝任何模組即可使用它。此外,使用者應該將所有模組與 async/await 語法一起使用。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP