Appearance
fetch
基于promise实现。
javascript
// get
fetch("http://localhost:3000/users")
.then(res=>{
if(res.ok){
return res.json()
}else{
return Promise.reject()
}
})
.then(res=>{
console.log(res)
}).catch(err=>{
console.log("err", err)
})
// post
fetch("http://localhost:3000/users",{
method: "post",
headers:{
// "content-type":"application/x-www-form-urlencoded"
"content-type":"application/json"
},
// body:"name=tom&age=100"
body:JSON.stringify({
name: "tom",
age: 100
})
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
// put
fetch("http://localhost:3000/users/2",{
method: "put",
headers:{
// "content-type":"application/x-www-form-urlencoded"
"content-type":"application/json"
},
// body:"name=tom&age=100"
body:JSON.stringify({
name: "tom",
age: 18
})
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
// PATCH
fetch("http://localhost:3000/users/2",{
method: "PATCH",
headers:{
// "content-type":"application/x-www-form-urlencoded"
"content-type":"application/json"
},
// body:"name=tom&age=100"
body:JSON.stringify({
name: "tom",
age: 18
})
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
// delete
fetch("http://localhost:3000/users/2",{
method: "delete",
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})