java - fetchAPI代替ajax請求為什么不走第二個then而直接走了catch?
問題描述
var serverUrl = 'http://43.254.150.58/b2c-web-cib'; //接口服務(wù)器fetch(serverUrl + ’/api/home/mallHome’, { method: ’post’, headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: ’json={}’}).then(function(response){ console.log(response.json()); return response.json();}).then(function(data){ console.log(data);}).catch(function(e) { console.log('出錯了');});
console出來的結(jié)果是這樣的Promise {[[PromiseStatus]]: 'pending', [[PromiseValue]]: undefined}出錯了我能肯定這個請求是成功的,而且展開這個Promise后是有值得,返回的值也正確,那到底哪里出了問題呢?為什么不走第二個then,而直接走了catch呢?我打印 一下這個catch里的參數(shù)e,結(jié)果是TypeError: Already read at test.html:19,意思是我在第一次then的時候已經(jīng)讀取過了
對了,如果我想用async/await代替Promise應(yīng)該怎么寫呢?
問題解答
回答1:問題出在你第一個then的console.log上
response是只能被讀取一次的,當(dāng)調(diào)用了bolb,json,text或者其他幾個讀取的接口之后,esponse的bodyUsed被設(shè)為true,就不能在此讀取了
console.log(response.json()); //第一次讀取return response.json(); //又讀取了一次
讀取了兩次,自然就報錯已經(jīng)讀取的錯誤了所以你把第一個then改成這樣就可以了
let jsonPromise = response.json() console.log(jsonPromise); return jsonPromise;
改成async/await的話,大概是這樣,不保證正確..
let doFetch = async () => { try {let resp = await fetch(serverUrl + ’/api/home/mallHome’, { method: ’post’, headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: ’json={}’})let json = await resp.json() } catch (e) {console.log('出錯了') }}
相關(guān)文章:
1. django - 后臺返回的json數(shù)據(jù)經(jīng)過Base64加密,獲取時用python如何解密~!2. css3 - 請問一下在移動端CSS布局布局中通常需要用到哪些元素,屬性?3. 我在centos容器里安裝docker,也就是在容器里安裝容器,報錯了?4. 我的html頁面一提交,網(wǎng)頁便顯示出了我的php代碼,求問是什么原因?5. tp6表單令牌6. angular.js - 如何通俗易懂的解釋“依賴注入”?7. docker 17.03 怎么配置 registry mirror ?8. node.js - node 客戶端socket一直報錯Error: read ECONNRESET,用php的socket沒問題哈。。9. 老哥們求助啊10. 在MySQL中新增字段時,報錯??
