如何使用JavaScript Fetch API获取数据
如今,JavaScript对于编写前端和后端代码非常有用。同时,它也是最广泛使用的编程语言。
而且,在开发实时应用程序时,我们需要从其他服务器获取数据。我们可以使用API(应用程序编程接口)从其他服务器或数据库获取数据。
在这里,我们将学习使用JavaScript获取数据的各种方法。
使用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()函数设置为异步函数。此外,我们使用await关键字与axios一起,以暂停函数的执行,直到我们从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()函数来调用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语法一起使用。