您的位置:首页 > 产品设计 > UI/UE

vue全局配置axios

2017-10-10 16:05 465 查看
由于尤雨溪之前在微博发布消息,不再继续维护vue-resource,并推荐大家开始使用 axios 。所以在现在的项目中就试着使用了axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。使用起来也比较方便。

安装

使用npm:

$ npm install axios


使用bower:

$ bower install axios


使用cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


配置使用

安装完成就可以使用了,这里我们就对Vue项目说一下。

在开发时,我们可以使用config进行axios的配置,还可以做一些请求拦截等。

首先,我们可以在src目录下创建untils文件夹来存放我们的配置文件。



配置如下:

'use strict'

import axios from 'axios'
import qs from 'qs'

axios.interceptors.request.use(config => {    // 这里的config包含每次请求的内容
// 判断localStorage中是否存在api_token
if (localStorage.getItem('api_token')) {
//  存在将api_token写入 request header
config.headers.apiToken = `${localStorage.getItem('api_token')}`;
}
return config;
}, err => {
return Promise.reject(err);
});

axios.interceptors.response.use(response => {
return response
}, error => {
return Promise.resolve(error.response)
});

function checkStatus (response) {
// 如果http状态码正常,则直接返回数据
if (response && (response.status === 200 || response.status === 304 ||
response.status === 400)) {
return response
}
// 异常状态下,把错误信息返回去
return {
status: -404,
msg: '网络异常'
}
}

function checkCode (res) {
// 如果code异常(这里已经包括网络错误,服务器错误,后端抛出的错误),可以弹出一个错误提示,告诉用户
if (res.status === -404) {
alert(res.msg)
}
if (res.data && (!res.data.success)) {
// alert(res.data.error_msg)
}
return res
}
// 请求方式的配置
export default {
post (url, data) {  //  post
return axios({
method: 'post',
baseURL: '/backapis',
url,
data: qs.stringify(data),
timeout: 5000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
},
get (url, params) {  // get
return axios({
method: 'get',
baseURL: '/backapis',
url,
params, // get 请求时带的参数
timeout: 5000,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
}
}


这里我们还可以配置拦截器,在处理 then 或 catch 之前拦截请求和响应。因为项目中后端同事处理过了,这里我就不配置了 哈哈~~~

接下来,在mainjs中引用就可以使用了

import axios from './untils/http';

//  这样就可以通过$axios发起请求了(个人使用喜好)
Vue.prototype.$axios = axios;


具体如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue-axios