对axios进行封装以及将API接口按业务模块统一管理,有助于我们简化代码,方便后期维护。
npm install axios
2.1、引入需要脚本,弹窗、axiso初始化
import axios from 'axios' import {Message } from 'element-ui' // 初始化axiso const service = axios.create({ // baseURL: "http:// setTimeout: 5000, // request timeout })
2.2、请求前处理
service.interceptors.request.use( config => { // do something before request is sent //比如,登录后每次请求携带token return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) } )
2.3、请求接口后,响应处理
service.interceptors.response.use( function (response) { let res = response.data; //根据接口返回状态判断 if (res.code != 0) { Message.error({ message: res.message || 'Error', }); return Promise.reject(res.message) } else { return Promise.resolve(res) } }, function (error) { // Do something with response error return Promise.reject(error); }
2.4 、get和post请求
export default { post(url, data, type = '') { return new Promise((resolve, reject) => { let config={} if(type == "form"){ config.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; } service.post(url, data ,config) .then(response => { resolve(response); }, err => { reject(err); }).catch((error) => { reject(error); }) }) }, get(url) { return new Promise((resolve, reject) => { service.get(url).then(response => { resolve(response.data); }, err => { reject(err); }).catch((error) => { reject(error); }) }) }, }
import request from '@/utils/request' import qs from "qs"; const path = "请求接口地址"; export default { //get请求参数对象格式化为一个字符串。例如let params = { c: 'b', a: 'd' };结果为c=b&a=d list(param) { return request.get(path + "/list?" + qs.stringify(param)) }, save(param) { return request.post(api_path + "/save", param) }, }
联系客服