介绍
曾经,人们使用 XMLHttpRequest 来发起 API 请求。它不支持 Promise,生成的 JavaScript 代码也不简洁。而使用 jQuery,你可以使用更简洁的 jQuery.ajax() 语法。.
现在,JavaScript 有自己内置的 API 请求方式。它就是 Fetch API,一种使用 Promise 发起服务器请求的新标准,并且还包含一些额外的功能。.
在本教程中,您将使用 Fetch API 创建 GET 和 POST 请求。.
先决条件
- 用于 Node.js 的本地开发环境。.
- 具备JavaScript编程基础知识。.
- 理解 JavaScript 中的 Promise。.
第一步 – Fetch API 语法入门
使用 Fetch API 的一种方法是将 fetch() API URL 作为参数传递:
fetch(url)
fetch() 方法返回一个 Promise 对象。在 fetch() 方法之后,插入 Promise 对象的 then() 方法:
fetch(url)
.then(function() {
// handle the response
})如果返回的 Promise 成功解析,则会执行 then() 方法内部的函数。该函数包含用于处理从 API 接收的数据的代码。.
在 then() 方法之后,插入 catch() 方法:
fetch(url)
.then(function() {
// handle the response
})
.catch(function() {
// handle the error
});您使用 `fetch()` 调用的 API 可能存在问题或其他错误。如果发生这种情况,则会返回被拒绝的 Promise。`catch` 方法用于处理这种拒绝。如果在调用 API 时发生错误,则会执行 `catch()` 中的代码。.
了解了 Fetch API 的语法之后,你就可以开始在实际 API 上使用 fetch() 了。.
步骤 2 – 使用 Fetch 从 API 获取数据
以下代码示例基于 JSONPlaceholder API。使用该 API,您将获取十位用户,并使用 JavaScript 将它们显示在页面上。本教程将从 JSONPlaceholder API 获取数据,并将其显示在作者列表的列表项中。.
首先创建一个 HTML 文件,并添加标题和包含作者 ID 的无序列表:
<h1>Authors</h1>
<ul id="authors"></ul>在 HTML 文件底部添加 script 标签,并使用 DOM 选择器获取 ul 元素。使用 getElementById 函数,并将作者信息作为参数:
<h1>Authors</h1>
<ul id="authors"></ul>
<script>
const ul = document.getElementById('authors');
</script>请记住,之前的 ul ID 是由作者创建的。.
然后创建一个 DocumentFragment 类型的列表:
<script>
// ...
const list = document.createDocumentFragment();
</script>所有附加的列表项都将添加到列表中。DocumentFragment 不属于活动文档树结构的一部分。这样做的好处是,当文档对象模型更改时,重新绘制不会影响性能。.
创建一个名为 url 的常量变量,用于保存返回十个随机用户的 API URL:
<script>
// ...
const url = 'https://jsonplaceholder.typicode.com/users';
</script>现在,使用 Fetch API,通过 fetch() 函数调用 JSONPlaceholder API,并将 url 作为参数:
<script>
// ...
fetch(url)
</script>您正在调用 Fetch API 并将 URL 传递给 JSONPlaceholder API。之后会收到响应。但是,您收到的响应并非 JSON 格式,而是一个包含一组方法的对象,您可以根据想要处理的信息来使用这些方法。请使用 json() 方法将返回的对象转换为 JSON 格式。.
添加一个 then() 方法,该方法包含一个带有名为 response 的参数的函数:
<script>
// ...
fetch(url)
.then((response) => {})
</script>response 参数接收 fetch(url) 返回的对象值。使用 json() 方法将响应转换为 JSON 数据:
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
</script>JSON 数据仍需处理。添加另一个 then() 语句,其中包含一个接受名为 data 的参数的函数:
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {})
</script>在这个函数中,创建一个名为 author 的变量,并将其值设置为 data:
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
})
</script>对于 authors 列表中的每个作者,您希望创建一个列表项来显示他们的姓名。map() 方法适用于这种模式:
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
});
})
</script>在你的 map 函数中,创建一个名为 li 的变量,并将其值设置为以 li(HTML 元素)为参数的 createElement 函数。此外,创建一个 h2 标签用于显示姓名,一个 span 标签用于显示邮箱地址:
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
let li = document.createElement('li');
let name = document.createElement('h2');
let email = document.createElement('span');
});
})
</script>h2 元素将包含作者姓名。span 元素将包含作者邮箱地址。innerHTML 属性和字符串插值功能可以实现这一点:
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
let li = document.createElement('li');
let name = document.createElement('h2');
let email = document.createElement('span');
name.innerHTML = `${author.name}`;
email.innerHTML = `${author.email}`;
});
})
</script>然后,使用 appendChild 方法将这些 DOM 元素添加到子元素中:
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
let li = document.createElement('li');
let name = document.createElement('h2');
let email = document.createElement('span');
name.innerHTML = `${author.name}`;
email.innerHTML = `${author.email}`;
li.appendChild(name);
li.appendChild(email);
list.appendChild(li);
});
})
ul.appendChild(list);
</script>请注意,每个列表项都会添加到 DocumentFragment 列表中。映射完成后,该列表会被添加到 ul 无序列表元素中。.
完成 then() 函数后,现在可以添加 catch() 函数了。该函数会将所有可能出现的错误记录到控制台:
<script>
// ...
fetch(url)
.then((response) => {
// ...
})
.then((data) => {
// ...
})
.catch(function(error) {
console.log(error);
});
// ...
</script>这是您创建的请求的完整代码:
<h1>Authors</h1>
<ul id="authors"></ul>
<script>
const ul = document.getElementById('authors');
const list = document.createDocumentFragment();
const url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
let li = document.createElement('li');
let name = document.createElement('h2');
let email = document.createElement('span');
name.innerHTML = `${author.name}`;
email.innerHTML = `${author.email}`;
li.appendChild(name);
li.appendChild(email);
list.appendChild(li);
});
}).
.catch(function(error) {
console.log(error);
});
ul.appendChild(list);
</script>您已成功使用 JSONPlaceholder API 和 Fetch API 发送了 GET 请求。接下来,您将发送 POST 请求。.
步骤 3 – 处理 POST 请求
Fetch 默认使用 GET 请求,但您也可以使用其他所有请求类型、更改请求头并发送数据。让我们创建一个 POST 请求。.
首先,添加一个常量变量,用于保存指向 JSONPlaceholder API 的链接:
const url = 'https://jsonplaceholder.typicode.com/users';
接下来,你需要设置你的对象,并将其作为第二个参数传递给 fetch 函数。这将是一个名为 data 的对象,其键名为 Sammy(或你的名字),值为:
// ...
let data = {
name: 'Sammy'
}由于这是一个 POST 请求,你需要明确指定。创建一个名为 fetchData 的对象:
// ...
let fetchData = {
}该对象应包含三个键:method、body 和 header:
// ...
let fetchData = {
method: 'POST',
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json; charset=UTF-8'
})
}方法键的值为“POST”。正文将设置为新创建的数据对象的 JSON.stringify 格式。标头的值为«Content-Type»: «application/json; charset=UTF-8”。.
Headers 接口是 Fetch API 的一项功能,允许您对 HTTP 请求和响应标头执行操作。.
通过添加这段代码,就可以使用 Fetch API 发送 POST 请求。你需要将 URL、fetchData 和参数添加到你的 Fetch POST 请求中:
// ...
fetch(url, fetchData)then() 函数包含处理从 JSONPlaceholder API 收到的响应的代码:
// ...
fetch(url, fetchData)
.then(function() {
// Handle response you get from the API
});这是您创建的请求的完整代码:
const url = 'https://jsonplaceholder.typicode.com/users';
let data = {
name: 'Sammy'
}
let fetchData = {
method: 'POST',
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json; charset=UTF-8'
})
}
fetch(url, fetchData)
.then(function() {
// Handle response you get from the API
});你也可以将 fetch() 传递给 Request 对象。.
const url = 'https://jsonplaceholder.typicode.com/users';
let data = {
name: 'Sammy'
}
let request = new Request(url, {
method: 'POST',
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json; charset=UTF-8'
})
});
fetch(request)
.then(function() {
// Handle response you get from the API
});通过这种方法,可以将请求作为 fetch() 的唯一参数,取代 url 和 fetchData。.
现在您已经了解了使用 Fetch API 创建和执行 POST 请求的两种方法。.
结果
虽然 Fetch API 目前尚未得到所有浏览器的支持,但它是 XMLHttpRequest 的绝佳替代方案。.









