axios簡單使用

      網友投稿 1225 2022-05-30

      @TOC

      一.JOSN Server使用:

      JsonServer主要的作用就是搭建本地的數據接口,創建json文件,便于調試調用。

      官方文檔

      npm install -g json-server

      建立一個名為db.josn的文件夾,寫入下面內容:

      { "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } }

      json-server --watch db.json

      \{^_^}/ hi! Loading db.json Done Resources http://localhost:3000/posts http://localhost:3000/comments http://localhost:3000/profile Home http://localhost:3000 Type s + enter at any time to create a snapshot of the database Watching...

      二.初識 axios 與配置:

      Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。

      axios中文文檔

      使用 npm:

      $ npm install axios

      使用cdn在頁面直接引用:

      三.axios基本使用:

      axios返回的是一個Promise結果。

      axios({ //請求類型 method:'get', //地址,用建好的 JSON Server地址 url: 'http://localhost:3000/posts/1', }).then(response=>{ console.log(response); })

      添加一篇文章:

      axios({ //請求類型 method:'post', //地址,用建好的 JSON Server url: 'http://localhost:3000/posts', //請求體 data:{ title:"哈哈", author:"北極光之夜。" } }).then(response=>{ console.log(response); })

      在db.josn文件里可以看到有添加結果了:

      更新上面那篇文章,id是2:

      axios({ //請求類型 method:'PUT', //地址,用建好的 JSON Server url: 'http://localhost:3000/posts/2', //請求體 data:{ title:"嘻嘻", author:"北極光之夜。" } }).then(response=>{ console.log(response); })

      刪除上面那篇文章:

      btns[3].addEventListener('click',()=>{ axios({ //請求類型 method:'delete', //地址,用建好的 JSON Server url: 'http://localhost:3000/posts/2', }).then(response=>{ console.log(response); }) })

      已經沒了:

      四.axios其它方式發送請求:

      有這么多:

      axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])

      來兩個例子:

      axios.request({ method:"get", url:"http://localhost:3000/posts" }).then(response=>{ console.log(response); })

      axios.post('http://localhost:3000/posts', { "title": "嘿嘿嘿", "author": "北極光之夜。" }).then(res=>{ console.log(res); })

      五.axios的默認配置:

      可以指定將被用在各個請求的配置默認值。

      原來:

      btns[0].addEventListener('click',()=>{ axios({ method: 'GET', url: 'http://localhost:3000/posts' }).then(res=>{ console.log(res); }) })

      相當于:

      axios的簡單使用

      //設置默認配置 axios.defaults.method = 'GET'; //默認請求為 get axios.defaults.baseURL = 'http://localhost:3000'; //設置基礎地址 btns[0].addEventListener('click',()=>{ axios({ url: '/posts' }).then(res=>{ console.log(res); }) })

      不止上面的,其它什么header,params等等配置都可以設置默認然后全局調用。

      六.axios創建實例對象發送請求:

      當有多個服務器需要發送請求時,這種方式比默認配置更方便。

      // 創建實例對象minyan,它的默認配置如下(用一個開源接口) const minyan = axios.create({ baseURL: 'http://poetry.apiopen.top', timeout: 2000 }) // 調用minyan,返回一句名言 minyan({ url:'/sentences' }).then(res=>{ console.log(res.data); }) // 創建實例對象shuju,它的默認配置如下 const shiju = axios.create({ baseURL: 'http://localhost:3000', timeout: 2000 }) // 調用shiju,返回自定義的json數據 shiju({ url:'/posts' }).then(res=>{ console.log(res.data); })

      這里實例對象的功能跟直接axios差不多一樣。

      timeout: 2000指請求超時則中斷。

      結果:

      七.axios-:

      在請求或響應被 then 或 catch 處理前攔截它們。

      就像一道道關卡,滿足要求放行,不滿足就攔截。

      跟promise很像的。

      其中config就是配置對象,可以進行更改的。

      // 添加請求- axios.interceptors.request.use(function (config) { // 在發送請求之前做些什么 console.log('請求成功嘍!'); return config; }, function (error) { // 對請求錯誤做些什么 console.log('請求失敗了~'); return Promise.reject(error); }); // 添加響應- axios.interceptors.response.use(function (response) { // 對響應數據做點什么 console.log('響應成功啦!'); return response; }, function (error) { // 對響應錯誤做點什么 console.log('響應失敗阿~'); return Promise.reject(error); }); //發送一個請求看看 axios({ method: 'GET', url: 'http://localhost:3000/posts' }).then(res=>{ console.log(res.data); })

      結果:

      // 添加請求- axios.interceptors.request.use(function (config) { // 在發送請求之前做些什么 console.log('請求成功嘍!'); // 拋錯 throw '參數有問題啊!'; }, function (error) { // 對請求錯誤做些什么 console.log('請求失敗了~'); return Promise.reject(error); }); // 添加響應- axios.interceptors.response.use(function (response) { // 對響應數據做點什么 console.log('響應成功啦!'); return response; }, function (error) { // 對響應錯誤做點什么 console.log('響應失敗阿~'); return Promise.reject(error); }); //請求 axios({ method: 'GET', url: 'http://localhost:3000/posts' }).then(res=>{ console.log(res.data); }).catch(reason=>{ console.log('最終失敗了'); })

      八.取消請求:

      因為在json-server本地調用速度太快,不利于查看效果,所以給json-server一個2秒的延遲執行。

      重新啟動,設置2秒延遲:

      json-server --watch db.json -d 2000

      基本用法:

      //2.聲明全局變量 let cancel = null; //點擊按鈕發送請求事件 btns[4].onclick = function(){ if(cancel!==null){ //取消上一次請求 cancel(); } axios({ method: 'GET', url: 'http://localhost:3000/posts', //1.添加配置對象屬性 cancelToken: new axios.CancelToken(function(c){ //3.將c值賦值給cancel cancel = c; }) }).then(res => { console.log(res.data); }) } //點擊按鈕取消請求事件 btns[5].onclick = function () { //4.直接調用這個函數就會取消請求了 cancel(); //重新初始化 cancel = null; }

      九. axios源碼分析:

      //構造函數 function Axios(config){ //初始化 this.defaults = config; this.intercepters = { request:{}, response:{} } } //原型添加相關方法 Axios.prototype.request = function(config){ console.log("發送ajax請求,類型為:"+config.method); } Axios.prototype.get = function(config){ return this.request({method:'GET'}); } Axios.prototype.post = function(config){ return this.request({method:'POST'}); } //聲明函數 function createInstance(config){ //實例化一個對象 let context = new Axios(config);//可以context.get(),context.post(),但是不能當函數用,context() //創建請求函數 let instance = Axios.prototype.request.bind(context);//instance是一個函數,可以instance({}),但不能instance.get(). //將Axios.prototype對象中方法添加到instance函數對象中 Object.keys(Axios.prototype).forEach(key=>{ instance[key]=Axios.prototype[key].bind(context); }); //為instance函數對象添加屬性default與intercept Object.keys(context).forEach(key=>{ instance[key]=context[key]; }); return instance; } //測試 let axios = createInstance(); axios({method:'post'});

      bind() 方法創建一個新的函數,在 bind() 被調用時,這個新函數的 this 被指定為 bind() 的第一個參數,而其余參數將作為新函數的參數,供調用時使用。

      Object.keys()方法會返回一個由一個給定對象的自身可枚舉屬性組成的數組,數組中屬性名的排列順序和正常循環遍歷該對象時返回的順序一致 。

      其它的封裝的方法就不說了~

      十.總結

      JavaScript JSON

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      上一篇:如何快速準備高質量的圖像分割的標注數據?
      下一篇:Onetab數據丟失之后!!!
      相關文章
      亚洲AV永久无码精品| 永久亚洲成a人片777777| 亚洲午夜无码久久久久| 夜色阁亚洲一区二区三区| 亚洲AV无码XXX麻豆艾秋| 亚洲精品无码国产片| 亚洲成AV人片在WWW| 亚洲av成人中文无码专区| 亚洲AV无码一区二区三区久久精品| 国产 亚洲 中文在线 字幕| 亚洲一区二区三区乱码在线欧洲| youjizz亚洲| 亚洲熟妇少妇任你躁在线观看| 亚洲中文字幕无码av永久| 亚洲人成网站18禁止| 亚洲av永久中文无码精品 | 亚洲成色999久久网站| 亚洲欧洲一区二区| 亚洲网站视频在线观看| 亚洲欧洲日产v特级毛片| 亚洲乱码日产精品BD在线观看| 亚洲AV成人噜噜无码网站| 国产成人精品日本亚洲直接| 亚洲熟妇无码AV| 亚洲第一区精品日韩在线播放| 亚洲国产一区二区视频网站| 国产亚洲精品影视在线产品| 亚洲国产成人片在线观看无码| 亚洲AV无码久久| 亚洲成A∨人片在线观看无码| 亚洲伊人久久大香线焦| 亚洲精品无码你懂的| 亚洲成?Ⅴ人在线观看无码| 亚洲美女在线国产| 国产日韩亚洲大尺度高清| 久久亚洲精品中文字幕| 亚洲综合色区中文字幕| 亚洲av永久中文无码精品 | 久久精品国产亚洲5555| 亚洲国产精品国自产拍AV| 久久久久亚洲Av无码专|