拿post和delete举例说明吧
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
http.js这个文件用来处理fetch请求,app.js设置初始的参数
关于fetch比较重要的是,fetch返回一个promise,fetch() API 仅在遇到"网络错误"时拒绝承诺,尽管这通常意味着权限问题或类似问题。基本上,fetch() 将拒绝承诺,如果用户脱机,或发生一些不太可能的网络错误,如 DNS 查找失败。
如果遇到网络故障,fetch() promise 将会 reject,带上一个 TypeError 对象。虽然这个情况经常是遇到了权限问题或类似问题——比如 404 不是一个网络故障。想要精确的判断 fetch() 是否成功,需要包含 promise resolved 的情况,此时再判断 Response.ok 是不是为 true。
好消息是,fetch提供了一个简单的 OK 标志,指示 HTTP 响应的状态代码是否处于成功范围内。例如,以下代码日志"错误:内部服务器错误(…)":
fetch("http://httpstat.us/500")
.then(function(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}).then(function(response) {
console.log("ok");
}).catch(function(error) {
console.log(error);
});
我们可以用fetch返回给我们的response里的ok属性,如果有错误就是true,那么有错误就throw这个错误,没有就返回reponse.json();,如果不用json的话fetch会返回response对象,我们并没法使用,如果打开proto属性看会看到json方法这样就可以获得具体的数据。
然后接着使用.then获取上一步的.json()然后resolve,我们就可以从app.js中使用.then获取到resolved的数据
http.js
class HTTP{ //es6 class
handleError(response){ //handle the error function
if (!response.ok) {
throw new Error(response.status);
}
return response.json();
}
post(url,data){
return new Promise((resolve,reject)=>{
fetch(url,{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(data)
}).then(this.handleError)
.then(data => resolve(data))
.catch(console.log)
})
}
delete(url) {
return new Promise((resolve, reject) => {
fetch(url, {
method: "DELETE",
headers: {
"Content-Type": "application/json"
}
})
.then(this.handleErrors)
.then(() => resolve("Deleted"))
.catch(console.log);
});
}
}
app.js
const http = new HTTP();
const data = {
name: "sam yao",
username: "moviegoer",
email: "yaob@miamioh.edu"
};
http
.post("https://jsonplaceholder.typicode.com/users", data)
.then(data => console.log(data));
http
.delete("https://jsonplaceholder.typicode.com/users/2")
.then(data => console.log(data));