<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
// 使用Promise封装fetch库(增删改查)
class EasyHttp{
// 封装get 请求
get(url){
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
// 封装 post 请求
post(url, data){
return new Promise((resolve, reject) => {
fetch(url, {
method:"POST",
headers:{
'Content-type': 'application/json'
},
body:JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
// 封装 put 请求
put(url, data){
return new Promise((resolve, reject) => {
fetch(url, {
method:"PUT",
headers:{
'Content-type': 'application/json'
},
body:JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
// 封装 delete 请求
delete(url, data){
return new Promise((resolve, reject) => {
fetch(url, {
method:"DELETE",
headers:{
'Content-type': 'application/json'
}
})
.then(res => res.json())
.then(data => resolve('数据删除成功!'))
.catch(err => reject(err))
})
}
}
const http = new EasyHttp;
// get请求数据
http.get('http://jsonplaceholder.typicode.com/users')
.then((data) => {
console.log(data)
})
.catch(err => console.log(err))
//post
const data = {
name:"xiangming",
username:"小明",
email:"1231231@qq.com"
}
http.post('http://jsonplaceholder.typicode.com/users',data)
.then((data) => console.log(data))
.catch(err => console.log(err))
//put
http.put('http://jsonplaceholder.typicode.com/users/2',data)
.then((data) => console.log(data))
.catch(err => console.log(err))
//delete
http.delete('http://jsonplaceholder.typicode.com/users/2')
.then((data) => console.log(data))
.catch(err => console.log(err))
</script>
</head>
<body>
</body>
</html>
ES6 使用Promise封装fetch库(增删改查)
最新推荐文章于 2024-05-31 10:34:50 发布