/**
* 封装fetch
*/
class EasyHttp{
async get(url){
const response = await fetch(url);
return await response.json();
}
async post(url,data){
const response = await fetch(url,{
method:'POST',
headers:{
"Content-Type":'application/json'
},
body:JSON.stringify(data)
})
return await response.json();
}
async put(url,data){
const response = await fetch(url,{
method:'PUT',
headers:{
"Content-Type":'application/json'
},
body:JSON.stringify(data)
})
return await response.json();
}
async delete(url){
const response = await fetch(url,{
method:'DELETE',
headers:{
"Content-Type":'application/json'
}
})
return await "删除成功";
}
}
调用
const http = new EasyHttp;
// http.get('https://jsonplaceholder.typicode.com/users')
// .then(data =>{
// console.log(data);
// })
// .catch(err =>{
// console.log(err);
// })
const data = {
name:'zlk',
username:'哈哈哈',
email:'4524718@qq.com'
}
// http.post('https://jsonplaceholder.typicode.com/users',data)
// .then(res =>{
// console.log(res);
// })
// .catch(err =>{
// console.log(err);
// })
// http.put('https://jsonplaceholder.typicode.com/users/2',data)
// .then(res => {
// console.log(res);
// })
// .catch(err =>{
// console.log(err);
// })
http.delete('https://jsonplaceholder.typicode.com/users/2')
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})