<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
// 使用Promise封裝fetch庫(增刪改查)
class EasyHttp{
// 封裝get 請求
async get(url){
const response = await fetch(url)
const resData = await response.json()
return resData
}
// 封裝 post 請求
async post(url, data){
const response = await fetch(url, {
method:"POST",
headers:{
'Content-type': 'application/json'
},
body:JSON.stringify(data)
})
const resData = await response.json()
return resData
}
// 封裝 put 請求
async put(url, data){
const response = await fetch(url, {
method:"PUT",
headers:{
'Content-type': 'application/json'
},
body:JSON.stringify(data)
})
const resData = await response.json()
return resData
}
// 封裝 delete 請求
async delete(url, data){
const response = fetch(url, {
method:"DELETE",
headers:{
'Content-type': 'application/json'
}
})
const resData = await "資料洗掉成功"
return resData
}
}
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/159566.html
標籤:AI
下一篇:Js原型鏈題目1
