使用Promise和Fetch的数据获取和错误处理

本文探讨了Fetch API返回的Promise如何处理HTTP错误状态,强调了即使HTTP响应为404或500,Promise也不会被拒绝。fetch只在网络故障时拒绝。通过Response.ok属性判断HTTP响应是否成功,结合Promise处理数据获取和错误。示例代码展示了如何在http.js和app.js中使用fetch获取和处理JSON数据。

拿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));
使用Fetch API获取JSON数据时,需要考虑多个层面的错误处理,以下是详细的方法示例代码: ### 1. 网络请求错误 当网络请求失败时,如无法连接到服务器,`fetch` 方法会返回一个被拒绝的 `Promise`。可以使用 `.catch()` 方法来捕获此类错误。 ```javascript fetch('https://example.com/data.json') .catch(error => { console.error('网络请求出错:', error); }); ``` ### 2. HTTP状态码错误 即使网络请求成功,服务器也可能返回非200的HTTP状态码(表示请求有问题)。需要检查响应的状态码。 ```javascript fetch('https://example.com/data.json') .then(response => { if (!response.ok) { throw new Error(`HTTP错误! 状态码: ${response.status}`); } return response.json(); }) .catch(error => { console.error('处理响应出错:', error); }); ``` ### 3. JSON解析错误 在尝试将响应数据解析为JSON时,可能会出现解析错误。可以在 `.then()` 中使用 `response.json()` 并捕获可能的解析错误。 ```javascript fetch('https://example.com/data.json') .then(response => { if (!response.ok) { throw new Error(`HTTP错误! 状态码: ${response.status}`); } return response.json(); }) .then(data => { // 使用解析后的JSON数据 console.log(data); }) .catch(error => { if (error instanceof SyntaxError) { console.error('JSON解析出错:', error); } else { console.error('其他错误:', error); } }); ``` ### 完整示例 ```javascript fetch('https://example.com/data.json') .then(response => { if (!response.ok) { throw new Error(`HTTP错误! 状态码: ${response.status}`); } return response.json(); }) .then(data => { console.log('成功获取JSON数据:', data); }) .catch(error => { if (error instanceof SyntaxError) { console.error('JSON解析出错:', error); } else { console.error('其他错误:', error); } }); ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值