前端 ---- Vue前端互動
阿新 • • 發佈:2020-09-21
Vue前端互動 Promise 1.promise的例項方法 1).then() 得到非同步任務正確的結果 2).catch() 獲取異常資訊 3).finally()成功與否都會執行(不是正式標準) 1.promise return 一個普通值會預設建立一個新的promise物件然後呼叫 2.promise 中的finally,不論成功與否,都會呼叫,但是.finally(function(data){console.log(data)})中的data是undefined,是沒有資料的 列子1: <script type="text/javascript"> /* 基於Promise傳送Ajax請求 */ function queryData(url) { var p = new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState != 4) return; if(xhr.readyState == 4 && xhr.status == 200) { // 處理正常的情況 resolve(xhr.responseText); }else{ // 處理異常情況 reject('伺服器錯誤'); } }; xhr.open('get', url); xhr.send(null); }); return p; } // queryData('http://localhost:3000/data') // .then(function(data){ // console.log(data); // },function(info){ // console.log(info) // }); // ============================ // 傳送多個ajax請求並且保證順序 queryData('http://localhost:3000/data1') .then(function(data){ console.log(data) return queryData('http://localhost:3000/data2') }) .then(function(data){ console.log(data); console.log('-----------------------------------------------------') return 'xiaoming' }) .then(function(data){ console.log(data); }) .finally(function (data) { // body... console.log('haha') }) </script> 2.promise的物件方法 1).all() `Promise.all`方法接受一個數組作引數,陣列中的物件(p1、p2、p3)均為promise例項(如果不是一個promise,該項會被用`Promise.resolve`轉換為一個promise)。它的狀態由這三個promise例項決定 (會把p1,p2,p3都執行了) 2).race()`Promise.race`方法同樣接受一個數組作引數。當p1, p2, p3中有一個例項的狀態發生改變(變為`fulfilled`或`rejected`),p的狀態就跟著改變。並把第一個改變狀態的promise的返回值,傳給p的回撥函式 (p1,p2,p3中的一個執行了,另外兩個會繼續傳送,但不會執行函式內容) all和race好像不能同時使用? fetch 1.概述 Fetch API是新的ajax解決方案 Fetch會返回Promise fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest物件 fetch(url, options).then() 例子1: <script type="text/javascript"> /* Fetch API 基本用法 fetch(url).then() 第一個引數請求的路徑 Fetch會返回Promise 所以我們可以使用then 拿到請求成功的結果 */ fetch('http://localhost:3000/fdata').then(function(data){ // text()方法屬於fetchAPI的一部分,它返回一個Promise例項物件,用於獲取後臺返回的資料 return data.text(); }).then(function(data){ // 在這個then裡面我們能拿到最終的資料 console.log(data); }) </script> 2.fetch API 中的 HTTP 請求 fetch(url, options).then() HTTP協議,它給我們提供了很多的方法,如POST,GET,DELETE,UPDATE,PATCH和PUT 1.預設的是 GET 請求 2.需要在 options 物件中指定對應的 method method:請求使用的方法 3.post 和 普通 請求的時候 需要在options 中設定請求頭 headers和body 這邊也分'Content-Type': 'application/x-www-from-urlencoded'和'application/json' 所以伺服器也分app.use(bodyParser.json())和app.use(bodyParser.urlencoded({ extended: false })); 例子2: <script type='text/javascript'> fetch('http://localhost:3000/fdata').then(function (argument) { // body... return argument.text() }).then(function (argument) { // body... console.log(argument) }) fetch('http://localhost:3000/books?id=123',{method:'get'}).then(function (argument) { // body... return argument.text() }).then(function (argument) { // body... console.log(argument) }) fetch('http://localhost:3000/books1/123',{method:'get'}).then(function (argument) { // body... return argument.text() }).then(function (argument) { // body... console.log(argument) }) fetch('http://localhost:3000/books2/123',{method:'delete'}).then(function (argument) { // body... return argument.text() }).then(function (argument) { // body... console.log(argument) }) POST請求傳參 fetch('http://localhost:3000/books3', { method: 'post', body: JSON.stringify({ uname: '張三', pwd: '456' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data){ return data.text(); }).then(function(data){ console.log(data) }); fetch('http://localhost:3000/books1/123', { method: 'put', body: JSON.stringify({ uname: '張三', pwd: '789' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data){ return data.text(); }).then(function(data){ console.log(data) }); </script> 3.fetchAPI 中 響應格式 響應結果分為text和JSON 用fetch來獲取資料,如果響應正常返回,我們首先看到的是一個response物件,其中包括返回的一堆原始位元組,這些位元組需要在收到後,需要我們通過呼叫方法將其轉換為相應格式的資料,比如`JSON`,`BLOB`或者`TEXT`等等 例子3: fetch('http://localhost:3000/json').then(function(data){ // return data.json(); // 將獲取到的資料使用 json 轉換物件 return data.text(); // // 將獲取到的資料 轉換成字串 }).then(function(data){ // console.log(data.uname) // console.log(typeof data) var obj = JSON.parse(data); console.log(obj.uname,obj.age,obj.gender) }) PS:text()方法屬於fetchAPI的一部分,它返回一個Promise例項物件,用於獲取後臺返回的資料 axios 1.傳參 如果使用params傳參,服務端是通過 xx.query.xx來獲得引數的,如ret.query.id,如果用params就是undefined 在POST中,現在用URLSearchParams來提交也是返回物件格式,而不是字串 PUT要傳ID進去,不然怎麼知道你更新的是哪個物件 2.全域性配置 在傳遞請求頭時,要到服務端允許該請求頭的跨域使用 # 配置公共的請求頭 axios.defaults.baseURL = 'https://api.example.com'; # 配置 超時時間 axios.defaults.timeout = 2500; # 配置公共的請求頭 axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; # 配置公共的 post 的 Content-Type axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 3.攔截器 1.請求攔截器 req 請求攔截器的作用是在請求傳送前進行一些操作 2.響應攔截器 res 響應攔截器的作用是在接收到響應後進行一些操作 例子: # 1. 請求攔截器 axios.interceptors.request.use(function(config) { console.log(config.url) # 1.1 任何請求都會經過這一步 在傳送請求之前做些什麼 config.headers.mytoken = 'nihao'; # 1.2 這裡一定要return 否則配置不成功 return config; }, function(err){ #1.3 對請求錯誤做點什麼 console.log(err) }) #2. 響應攔截器 axios.interceptors.response.use(function(res) { #2.1 在接收響應做些什麼 var data = res.data; return data; }, function(err){ #2.2 對響應錯誤做點什麼 console.log(err) }) 4.async await後面要接promise例項物件 1.async作為一個關鍵字放到函式前面 2.任何一個async函式都會隱式返回一個`promise` 3.await關鍵字只能在使用async定義的函式中使用 4.await後面可以直接跟一個 Promise例項物件 5.await函式不能單獨使用