vue fetch中的.then()的正確使用方法
先看一段代碼:
fetch(’http://localhost:3000/books?id=123456’,{ method:’get’}).then(function(value1){ console.log(value1); return ’hello’;}).then(function(value2){ console.log(value2); return ’HelloWorld’;})/*.then(function(data){ console.log(data); return data.text(); })*/.then(data=>{ console.log(data);})
// 接口app.get(’/books’, (req, res) => { res.send(’傳統(tǒng)的URL傳遞參數(shù)!’ + req.query.id)})
在這段代碼中我們發(fā)現(xiàn),最初傳入的是一個(gè)對(duì)象,緊接著后一個(gè).then()的傳入?yún)?shù)使用了前一個(gè).then()的返回值,換句話說,就是后一個(gè)then使用前一個(gè)then的封裝結(jié)果
那么現(xiàn)在去掉注釋:
.then(function(value2){ console.log(value2); return ’HelloWorld’;}).then(function(data){ console.log(data); return data.text(); })text()方法屬于fetch API的一部分,返回一個(gè)Promise實(shí)例對(duì)象,用于獲取后臺(tái)返回的數(shù)據(jù)
這段代碼中,傳入的data是上一步封裝的字符串,所以此時(shí)用data.text()報(bào)錯(cuò),除非data為對(duì)象
下面演示正確使用方式:
fetch(’http://localhost:3000/books?id=123456’,{ method:’get’}).then(function(data){ console.log(data); console.log(typeof(data)); return data.text();}).then(data=>{ console.log(data); console.log(typeof(data));})
輸出了接口詢問的內(nèi)容,為String類型
到此這篇關(guān)于vue fetch中的.then()的正確使用方法的文章就介紹到這了,更多相關(guān)vue fetch .then()內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向2. Nginx+php配置文件及原理解析3. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼4. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題5. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析6. 淺談python出錯(cuò)時(shí)traceback的解讀7. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法8. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解9. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)10. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法
