<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
class EasyHttp{
get(url){
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
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(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(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;
http.get('http://jsonplaceholder.typicode.com/users')
.then((data) => {
console.log(data)
})
.catch(err => console.log(err))
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))
http.put('http://jsonplaceholder.typicode.com/users/2',data)
.then((data) => console.log(data))
.catch(err => console.log(err))
http.delete('http://jsonplaceholder.typicode.com/users/2')
.then((data) => console.log(data))
.catch(err => console.log(err))
</script>
</head>
<body>
</body>
</html>