axios的使用浅谈
2018-02-24 14:26
274 查看
axios的使用
1.安装axios$ npm install axios
2.创建一个axios实例
import axios from 'axios' // 创建axios实例 const service = axios.create({ baseURL: baseURL, // api的base_url timeout: 10000, // 请求超时时间 transformRequest: [(data) => { // 对 data 进行任意转换处理 // let body = new URLSearchParams(); // let body = new FormData(); if(typeof data === 'object' && data !== null) { Object.keys(data).forEach(item => { if(data[item] !== null && data[item] !== undefined && data[item] !== '') { if(Array.isArray(data[item])) { body.append(item, JSON.stringify(data[item])) } else { body.append(item, data[item]) } } }) return body; } return data; // return JSON.stringify(data) }] }); axios.defaults.withCredentials = true // 自动获取cookie
3.request拦截器
// request拦截器 service.interceptors.request.use(config => { // config.headers.post['Content_Type'] = 'application/json' config.headers['Content-Type'] = 'application/json' // 改变data的数据格式 return config }, error => { // Do something with request error console.log(error) // for debug Promise.reject(error) })
4.respone拦截器
// respone拦截器 service.interceptors.response.use( /** * 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页 * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中 */ response => { return response }, error => { console.log('err' + error)// for debug return Promise.reject(error) } )
5.导出
export default service
调用axios方法(例子)
1.调用接口Api// 导入该方法 import fetch from '../config/fetch.js' // get请求 params post请求 data // 获取商品列表 export function msiteFoodTypes (opt) { return fetch({ url: '/v2/index_entry', method: 'get', params: opt }) } // 登录 /** *@param username 用户名 Y *@param password 密码 Y *@param captcha_code 验证码 Y */ export function login (opt) { return fetch({ url: '/v2/login', method: 'post', data: opt }) }
相关文章推荐
- 浅谈 Axios 在 Vue 项目中的使用
- 浅谈 Axios 在 Vue 项目中的使用
- java使用axios.js的post请求后台时无法接收到参数的问题
- 浅谈Android系统开发中LOG的使用
- 浅谈render_to_response()使用
- MVP浅谈,使用Swift语言完成登录界面的Demo
- axios使用拦截器统一处理所有的http请求的方法
- 浅谈VB编程中网格控件的选用及使用方法
- vue-cli(vue2.x)中使用axios
- 浅谈hibernate annotation的使用
- 浅谈C#中正则表达式的使用
- 浅谈Jquery的使用下篇
- 浅谈使用expect实现自动交互式(2)
- 浅谈使用jQuery实现Ajax
- 浅谈Android Studio 3.0 工具新特性的使用 Android Profiler 、Device File Explorer
- iOS开发之浅谈GCD的使用(二)
- 浅谈mysql的使用权限以及用户安全
- 浅谈SQLServer行列转换PIVOT函数的使用
- (浅谈)Java反射机制的使用
- 浅谈Android Fragment嵌套使用存在的一些BUG以及解决方法