vue中axios调用分装的请求方法(get/post方式)
程序员文章站
2022-07-08 10:09:53
封装请求文件import axios from 'axios';import qs from 'qs'import {Notify} from 'vant';// const baseUrl = "http://192.168.0.100:8000";const instance = axios.create({baseURL: 请求接口地址前缀,timeout: 15000,// Authorization:""});// 添加请求拦截器instance.interc...
封装请求文件
import axios from 'axios';
import qs from 'qs'
import { Notify } from 'vant';
// const baseUrl = "http://192.168.0.100:8000";
const instance = axios.create({ baseURL: 请求接口地址前缀, timeout: 15000, // Authorization:"" });
// 添加请求拦截器
instance.interceptors.request.use(function(config) { // 在发送请求之前做些什么
return config; }, function(error) { Notify({ message: 'The request failed to send!', color: '#ad0000', background: '#ffe1e1', });
return Promise.reject(error); });
// 添加响应拦截器
instance.interceptors.response.use(function(response) { // 对响应数据做点什么
return response; }, function(error) { Notify({ message: 'Data response failed!', color: '#ad0000', background: '#ffe1e1', });
// 对响应错误做点什么
return Promise.reject(error); });
/**
* 封装get方法
* @param url
* @param data
* @returns {Promise} */
export function get(url, params, sucess, fail, complete) { return new Promise((resolve, reject) => { instance.get(url, { params: params })
.then(response => { complete();
errorMsg(response); })
.catch(err => { fail();
complete();
reject(err) }) }) } /**
* 封装post请求
* @param url
* @param data
* @returns {Promise} */
export function post(url, data, complete) { return new Promise((resolve, reject) => { instance.post(url, data)
.then(response => { complete();
resolve(response); }, err => { complete();
reject(err)
Notify({ message: 'Data response failed!', color: '#ad0000', background: '#ffe1e1', }); }) }).then(errorMsg) } /**
* 封装postJson请求
* @param url
* @param data
* @returns {Promise} */
export function postJson(url, data, complete) { return new Promise((resolve, reject) => { instance.post(url, qs.stringify(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' } })
.then(response => { complete();
resolve(response); }, err => { complete();
reject(err)
Notify({ message: 'Data response failed!', color: '#ad0000', background: '#ffe1e1', }); }) }).then(errorMsg) } /**
* @param {Object} response自定义错误信息
*/
function errorMsg(response) { console.log(response)
return new Promise((resolve, reject) => { if (response.status === 200) { if (response.data.code != 200) { reject(response) } else { resolve(response.data); } } else { Notify({ message: 'Data response failed!', color: '#ad0000', background: '#ffe1e1', });
reject(response) } }) }
全局引用
import {get,post,postJson} from './common/http'
Vue.prototype.$get = get
Vue.prototype.$post = post
Vue.prototype.$postJson = postJson
调用
this.$post(接口, 参数, function() { //这里是无论成功或者失败都会执行的方法 }).then(function(res) { //请求成功 返回数据 }, (err) => { //请求失败 执行其他操作 })
本文地址:https://blog.csdn.net/qq_42267888/article/details/107864949