使用fetch API进行简单的DELETE请求,使用自定义的HTTP库
为什么要使用fetch() API方法
fetch()方法用于在不刷新页面的情况下向服务器发送请求。它是XMLHttpRequest对象的一种替代方法。我们将使用一个虚拟的API作为示例,该API包含一个数组,并且通过fetch API方法和自定义的HTTP库来展示DELETE数据。本教程中使用的API链接为:https://jsonplaceholder.typicode.com/users/2
前提条件: 你应该对HTML、CSS和JavaScript有基本的了解。
说明: 首先我们需要创建一个index.html文件,并将下述代码粘贴到index.html文件中。index.html文件包含在body标签底部的library.js和app.js文件。
现在在library.js文件中,首先创建一个ES6类DeleteHTTP,其中包含一个async fetch()函数,用于从API中DELETE数据。其中使用了两个await阶段,第一个是用于fetch(),第二个是用于它的响应。无论我们接收到什么响应,都会将其返回给app.js文件中的调用函数。
现在在app.js文件中,首先实例化DeleteHTTP类,然后通过http.delete原型函数将URL发送到library.js文件。此外,还有两个要解析的Promise。第一个是用于任何响应数据,第二个是用于任何错误。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"
content="ie=edge">
<title>DELETE Request</title>
</head>
<body>
<h1>
Simple DELETE request using fetch
API by making custom HTTP library
</h1>
<!-- Including library.js and app.js -->
<script src="library.js"></script>
<script src="app.js"></script>
</body>
</html>
library.js
// ES6 class
class DeleteHTTP {
// Make an HTTP PUT Request
async delete(url) {
// Awaiting fetch which contains
// method, headers and content-type
const response = await fetch(url, {
method: 'DELETE',
headers: {
'Content-type': 'application/json'
}
});
// Awaiting for the resource to be deleted
const resData = 'resource deleted...';
// Return response data
return resData;
}
}
文件名:app.js
// Instantiating new EasyHTTP class
const http = new DeleteHTTP;
// Update Post
http.delete('https://jsonplaceholder.typicode.com/users/2')
// Resolving promise for response data
.then(data => console.log(data))
// Resolving promise for error
.catch(err => console.log(err));
输出: 打开浏览器中的 index.html 文件,然后 右键点击->检查元素->控制台。 对于DELETE请求,您将看到以下输出: