浅谈 Axios 在 Vue 项目中的使用
2018-03-25 22:05
405 查看
介绍
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。特性
它主要有如下特性:浏览器端发起XMLHttpRequests请求Node端发起http请求
支持Promise API
拦截请求和响应
转化请求和响应(数据)
取消请求
自动转化json数据
客户端支持抵御XSRF(跨站请求伪造)
安装
Vue项目中使用如下命令安装npm install axios --save使用
Axios拥有诸多配置项,由于项目中请求数量很多,因此考虑将其封装成公共API,api.js调用一个配置文件config.jsapi.jsimport axios from 'axios' import config from './config.js' class API { // POST post(params) { config.data = params.data return axios.post(params.url,config.data,config) } // 此处可以封装其他方法 } export default APIconfig.js
export default { method: 'post', // 基础url前缀 baseURL: 'your request url', // 请求头信息 headers: { 'Content-Type':'application/json;charset=UTF-8' }, // 参数 data: {}, // 设置超时时间 timeout: 10000, // 携带凭证 withCredentials: false, // 返回数据 f835 类型 responseType: 'json' } getBrandsByHot:function () { let params = { url:'/company/list', data:{ cond:{}, limit:9, order_word: "attention_rate", order_direction: -1, page:1 } } api.post(params).then(response => { this.hot_brand = response.data }).catch({}); }由于IE9不支持Promise,因此需要在项目入口main.js中打个补丁,否则无法发出请求
import 'babel-polyfill'如上,已经能在IE9+上发起网络请求,但是IE9上有个问题:response.data为undefined,因此需要对返回的数据针对不同浏览器进行处理,在API.js中加入如下拦截器
// 响应拦截 axios.interceptors.response.use(function (response) { var data // IE9时response.data是undefined,因此需要使用response.request.responseText(Stringify后的字符串) if(response.data == undefined){ data = response.request.responseText } else{ data = response.data } // 判断data不是Object时,解析成Object if(!(data instanceof Object)){ data = JSON.parse(data) } return data }, function (error) { return Promise.reject(error) });
进阶使用
结合promise 统一请求进一步封装成vue插件 可实现登录、拦截、登出等功能,以及利用axios的http拦截器拦截请求和响应api.js
export default function fetch (options) { return new Promise((resolve, reject) => { const instance = axios.create({ baseURL: SERVER_BASE_URL, headers: {}, transformResponse: [function (data) { }] }) instance.interceptors.request.use( config => { return config }, err => { return Promise.reject(err) }) instance.interceptors.response.use( response => { return response }, error => { return Promise.reject({code:1000}) // 返回接口返回的错误信息 }) //请求处理 instance(options) .then((res) => { resolve(res.data) return false }) .catch((error) => { reject(error) }) }) }然后我们可以吧请求放到一个文件统一维护(相同的请求再也不用写多次了)
interface.js
const IS_GUEST = params => { return fetch({ url: '/sys/role/getRoleIdByUserId', method: 'get', params: params }) } const RESET_PASSWORD = params => { return fetch({ url: '/person/resetPswByMobile', method: 'get', params: params }) } export default apiList={ IS_GUEST, RESET_PASSWORD }再来把封装的axio作为vue的插件使用
index.js
//导入模块 import apiList from './interface' const install = function(Vue) { if (install.installed) return install.installed = true Object.defineProperties(Vue.prototype, { $api: { get() { return apiList } } }) } export default { install }接下来我们vue中可以这样使用axios
main.js先注册插件
import api from './index' Vue.use(api)然后可以在任何文件愉快的使用起来 就像这样
this.$api.RESET_PASSWORD().then(res=>{ // ... })
相关文章推荐
- 浅谈 Axios 在 Vue 项目中的使用
- vue项目使用axios发送请求让ajax请求头部携带cookie
- vue项目使用axios发送请求让ajax请求头部携带cookie的方法
- 在vue项目中,使用axios跨域处理
- 基于vue-cli的vue项目之axios的使用2--最基础的请求
- 封装axios在vue-cli项目中便捷使用
- 使用vue-cli+axios构建的项目本地环境API代理设置和解决跨域
- 基于vue-cli的vue项目之axios的使用5--axios方法发送请求
- vue项目中,使用axios跨域处理
- 基于vue-cli的vue项目之axios的使用4--并发请求
- 基于vue-cli的vue项目之axios的使用1--准备工作
- 基于vue-cli的vue项目之axios的使用6--配置axios
- vue项目中使用axios上传图片等文件操作
- 详解vue-cli 构建项目 vue-cli请求后台接口 vue-cli使用axios、sass、swiper
- vue2.0项目实战(3)使用axios发送请求
- 基于vue-cli的vue项目之axios的使用4--并发请求
- 基于vue-cli的vue项目之axios的使用3--get传参请求
- vue项目中使用jQuery
- 使用vue-cli启动项目出错
- vue-cli的使用,创建项目,教程,上手,vue脚手架的使用