<p><code></p> <p>Ax<a href="http://www.js-code.com/tag/ios" title="ios" target="_blank">ios</a> 是一个基于 promise 的 HTTP 库,可以用在浏览器和 <a href="http://www.js-code.com/tag/node" title="node" target="_blank">node</a>.js 中。在vue项目之中使用ax<a href="http://www.js-code.com/tag/ios" title="浏览关于“ios”的文章" target="_blank" class="tag_link">ios</a>是一个非常明智的选择,因为vue官方已经宣称不再维护vue-resource,并且推荐使用axios.</p> <p>1 为什么选择axios?</p> <ol> <li>使用axios可以统一做请求-响应拦截,例如响应时我们将响应信息拦截起来,判断状态码,从而弹出报错信息</li> <li>设定请求超时,例如3000ms未响应则停止请求</li> <li>基于promise,可以很方便地使用then或者catch来处理请求</li> <li>自动转换json数据</li> </ol> <p>2 如何使用?</p> <p>可以使用以下方式</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="1. npm install axios --save 2. bower install axios --save 3. <script src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;></script><br /> " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs sql"><code>1. npm <span class="hljs-keyword">install</span> axios <span class="hljs-comment">--save</span> <span class="hljs-number">2.</span> bower <span class="hljs-keyword">install</span> axios <span class="hljs-comment">--save</span> <span class="hljs-number">3.</span> &lt;script src=<span class="hljs-string">"https://unpkg.com/axios/dist/axios.min.js"</span>&gt;&lt;/script&gt; </code></pre> <p>3 封装http请求<br />官网给定的实例:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="axios.get('/user?ID=12345') .then(function(response){ console.log(response); }) .catch(function(err){ console.log(err); });" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs lua"><code>axios.get(<span class="hljs-string">'/user?ID=12345'</span>) .<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(response)</span></span>{ console.<span class="hljs-built_in">log</span>(response); }) .catch(<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(err)</span></span>{ console.<span class="hljs-built_in">log</span>(err); });</code></pre> <p>在此基础上我们应该再次封装http中的post get put de<a href="http://www.js-code.com/tag/let" title="let" target="_blank">let</a>e方法,在具体页面只需要调用接口函数以及传入params即可,其余例如url,header之类的我们应该进行封装。<br />例如在index.vue之中使用一个函数来实现通过id来获取对应的用户信息,返回结果在then方法的result之中</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="API.getUserInfo({id:'01'}).then((result)=>{})" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs coffeescript"><code style="word-break: break-word; white-space: initial;"><a href="http://www.js-code.com/tag/api" title="浏览关于“API”的文章" target="_blank" class="tag_link">API</a>.getUserInfo({id:<span class="hljs-string">'01'</span>}).<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">(result)</span>=&gt;</span>{})</code></pre> <p>4 实现思路<br />新建一个文件,构建一个axios对象实例 例如axios.js</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="import axios from 'axios'; import router from '../router'; // 创建axios实例 const service = axios.create({ timeout: 30000 // 请求超时时间 }) // 添加request拦截器 service.interceptors.request.use(config => {<br /> return config<br /> }, error => {<br /> Promise.reject(error)<br /> })<br /> // 添加respone拦截器<br /> service.interceptors.response.use(<br /> response => {<br /> let res={};<br /> res.status=response.status<br /> res.data=response.data;<br /> return res;<br /> },<br /> error => {<br /> if(error.response &amp;&amp; error.response.status == 404){<br /> router.push('/blank.vue')<br /> }</p> <p> return Promise.reject(error.response)<br /> }<br /> )</p> <p>export function get(url, params = {}) {<br /> params.t = new Date().getTime(); //get方法加一个时间参数,解决ie下可能缓存问题.<br /> return service({<br /> url: url,<br /> method: 'get',<br /> headers: {<br /> },<br /> params<br /> })<br /> }</p> <p>//封装post请求<br /> export function post(url, data = {}) {<br /> //默认配置<br /> let sendObject={<br /> url: url,<br /> method: 'post',<br /> headers: {<br /> 'Content-Type':'application/json;charset=UTF-8'<br /> },<br /> data:data<br /> };<br /> sendObject.data=JSON.stringify(data);<br /> return service(sendObject)<br /> }</p> <p>//封装put方法 (resfulAPI常用)<br /> export function put(url,data = {}){<br /> return service({<br /> url: url,<br /> method: 'put',<br /> headers: {<br /> 'Content-Type':'application/json;charset=UTF-8'<br /> },<br /> data:JSON.stringify(data)<br /> })<br /> }<br /> //删除方法(resfulAPI常用)<br /> export function deletes(url){<br /> return service({<br /> url: url,<br /> method: 'delete',<br /> headers: {}<br /> })<br /> }</p> <p>//不要忘记export<br /> export {<br /> service<br /> }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>; <span class="hljs-keyword">import</span> router <span class="hljs-keyword">from</span> <span class="hljs-string">'../router'</span>; <span class="hljs-comment">// 创建axios实例</span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/const" title="浏览关于“const”的文章" target="_blank" class="tag_link">const</a></span> service = axios.create({ timeout: <span class="hljs-number">30000</span> <span class="hljs-comment">// 请求超时时间 </span> }) <span class="hljs-comment">// 添加request拦截器 </span> service.interceptors.request.use(<span class="hljs-function"><span class="hljs-params">config</span> =&gt;</span> { <span class="hljs-keyword">return</span> config }, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> { <span class="hljs-built_in"><a href="http://www.js-code.com/tag/promise" title="浏览关于“Promise”的文章" target="_blank" class="tag_link">Promise</a></span>.reject(error) }) <span class="hljs-comment">// 添加respone拦截器</span> service.interceptors.response.use( <span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> { <span class="hljs-keyword"><a href="http://www.js-code.com/tag/let" title="浏览关于“let”的文章" target="_blank" class="tag_link">let</a></span> res={}; res.status=response.status res.data=response.data; <span class="hljs-keyword">return</span> res; }, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> { <span class="hljs-keyword">if</span>(error.response &amp;&amp; error.response.status == <span class="hljs-number">404</span>){ router.push(<span class="hljs-string">'/blank.vue'</span>) } <span class="hljs-keyword">return</span> <span class="hljs-built_in"><a href="http://www.js-code.com/tag/promis" title="浏览关于“Promis”的文章" target="_blank" class="tag_link">Promis</a>e</span>.reject(error.response) } ) <span class="hljs-keyword"><a href="http://www.js-code.com/tag/export" title="浏览关于“export”的文章" target="_blank" class="tag_link">export</a></span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span>(<span class="hljs-params">url, params = {}</span>) </span>{ params.t = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime(); <span class="hljs-comment">//get方法加一个时间参数,解决ie下可能缓存问题.</span> <span class="hljs-keyword">return</span> service({ url: url, method: <span class="hljs-string">'get'</span>, headers: { }, params }) } <span class="hljs-comment">//封装post请求</span> <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">post</span>(<span class="hljs-params">url, data = {}</span>) </span>{ <span class="hljs-comment">//默认配置 </span> <span class="hljs-keyword">let</span> sendObject={ url: url, method: <span class="hljs-string">'post'</span>, headers: { <span class="hljs-string">'Content-Type'</span>:<span class="hljs-string">'application/json;charset=UTF-8'</span> }, data:data }; sendObject.data=<span class="hljs-built_in">JSON</span>.stringify(data); <span class="hljs-keyword">return</span> service(sendObject) } <span class="hljs-comment">//封装put方法 (resfulAPI常用)</span> <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">put</span>(<span class="hljs-params">url,data = {}</span>)</span>{ <span class="hljs-keyword">return</span> service({ url: url, method: <span class="hljs-string">'put'</span>, headers: { <span class="hljs-string">'Content-Type'</span>:<span class="hljs-string">'application/json;charset=UTF-8'</span> }, data:<span class="hljs-built_in">JSON</span>.stringify(data) }) } <span class="hljs-comment">//删除方法(resfulAPI常用)</span> <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deletes</span>(<span class="hljs-params">url</span>)</span>{ <span class="hljs-keyword">return</span> service({ url: url, method: <span class="hljs-string">'delete'</span>, headers: {} }) } <span class="hljs-comment">//不要忘记export</span> <span class="hljs-keyword">export</span> { service }</code></pre> <p>上述代码主要实现一个基本的axios封装,请求成功时获取响应对象,我们主需要获取几个有用的信息即可,例如状态码,数据即可,同时处理错误,例如返回404我们跳转到一个新界面</p> <p>封装接口函数<br />新建文件,例如api.js</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="import {get, post,deletes,put} from './axios.js' ;//导入axios实例文件中方法 let bsae_api = process.env.BASE_API ? './'+process.env.BASE_API :'..' //获取项目api请求地址 //根据id获取用户信息 export const getUserInfoById=(id)=>{<br /> return get(`${bsae_api}/web/user/${id}`); //resfulapi风格<br /> }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword">import</span> {<span class="hljs-keyword">get</span>, post,deletes,put} <span class="hljs-keyword">from</span> <span class="hljs-string">'./axios.js'</span> ;<span class="hljs-comment">//导入axios实例文件中方法</span> <span class="hljs-keyword">let</span> bsae_api = process.env.BASE_API ? <span class="hljs-string">'./'</span>+process.env.BASE_API :<span class="hljs-string">'..'</span> <span class="hljs-comment">//获取项目api请求地址</span> <span class="hljs-comment">//根据id获取用户信息</span> <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getUserInfoById=<span class="hljs-function">(<span class="hljs-params">id</span>)=&gt;</span>{ <span class="hljs-keyword">return</span> <span class="hljs-keyword">get</span>(<span class="hljs-string">`<span class="hljs-subst">${bsae_api}</span>/web/user/<span class="hljs-subst">${id}</span>`</span>); <span class="hljs-comment">//resfulapi风格</span> }</code></pre> <p>具体页面使用 index.vue</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="import API from '@/utils/api' getUserInfo(){ API.getUserInfoById('01).then((result)=>{<br /> }).catch((error)=>{<br /> })<br /> }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs erlang"><code>import API from '@/utils/api' <span class="hljs-function"><span class="hljs-title">getUserInfo</span><span class="hljs-params">()</span>{ API.<span class="hljs-title">getUserInfoById</span><span class="hljs-params">('<span class="hljs-number">01</span>)</span>.<span class="hljs-title">then</span><span class="hljs-params">((result)</span>=&gt;{ }).<span class="hljs-title">catch</span><span class="hljs-params">((error)</span>=&gt;{ }) }</span></code></pre> <p>以上就是一些axios封装的基本介绍</p> <p></code></p>

本文固定链接: http://www.js-code.com/vue-js/vue-js_27182.html