欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

axios 封装

程序员文章站 2024-01-12 08:32:16
调用 ......
来自:https://www.jianshu.com/p/68d81da4e1ad 侵删

import axios from 'axios' import qs from 'qs' let baseurl = 'http://localhost:8081/api' function getrequest (apipath, params, successcallback, errorcallback) { let url = baseurl + apipath let req = axios.get(url, { params: params, paramsserializer: params => { return qs.stringify(params, { indices: false }) }}) thenresponse(req, successcallback, errorcallback) } function postrequest (apipath, params, successcallback, errorcallback) { let url = baseurl + apipath let req = axios.post(url, qs.stringify(params, { indices: false })) thenresponse(req, successcallback, errorcallback) } function putrequest (apipath, params, successcallback, errorcallback) { let url = baseurl + apipath // var params = new urlsearchparams() // params.append('status', 0) let req = axios.put(url, qs.stringify(params, { indices: false })) thenresponse(req, successcallback, errorcallback) } function deleterequest (apipath, params, successcallback, errorcallback) { let url = baseurl + apipath let req = axios.delete(url, { params: params, paramsserializer: params => { return qs.stringify(params, { indices: false }) }}) thenresponse(req, successcallback, errorcallback) } /** * 请求结果处理 * @param axiosrequest * @param successcallback * @param errorcallback */ function thenresponse (axiosrequest, successcallback, errorcallback) { axiosrequest.then((res) => { if (res.status === 200) { res = res.data if (res.code === 0) { if (successcallback) successcallback(res) } else { if (errorcallback) errorcallback(res.code, res.msg) } } }).catch((error) => { if (errorcallback) errorcallback(-1, error.message) }) } export { getrequest, postrequest, putrequest, deleterequest }

调用

//导入封装axios的js文件
import {getrequest, deleterequest} from 'utils/api'
//发送delete请求,带数组参数 与 普通参数
deleterequest('/admin/user/del', {
        token: ‘sdfsdifjsiodfkmsdofm,sdopfk’,
        ids: [1,2,3,4,5,6]
      }, function (res) {
        _this.$alert('删除成功')
      }, function (errcode, errmsg) {
        _this.$alert('code ' + errcode + ' ,meaasge ' + errmsg)
      })
//发送get请求
getrequest('/admin/users', {
        status: 0,
        pagenum: this.currentpage,
        pagesize: count,
        token: '111'
      }, function (res) {
        _this.totalpage = res.data.total
      }, function (errcode, errmsg) {
        _this.$alert('code ' + errcode + ' ,meaasge ' + errmsg)
      })