【bug】axios请求mock.js失败

10 篇文章 0 订阅

【vue】mock.js安装及使用

问题描述

post请求失败

请求没反应

get请求失败

返回页面HTML
.vue

this.$get('/gettest', {b:'222}, (res) => {
      console.log(res)
    })
this.$post('/posttest', {a:'111'}, (res) => {
      console.log(res)
    })

mock.js

Mock.mock('/gettest', 'get', opt => {
  console.log(opt)
  return 'get test success'
})
Mock.mock('/posttest', 'post', opt => {
  console.log(opt)
  return 'posttest success'
})

axios-config.js配置

...
axios.interceptors.request.use(
  config => {
    // 请求响应时间
    config.timeout = 60 * 1000
    // config.data = JSON.stringify(config.data)
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
      // 'Content-Type': 'application/json'//默认
    }
    return config
  },
  function (error) {
    // 对请求错误做处理
    return Promise.reject(error)
  }
)

const get = (url, data = {}, success = () => {}, failure = () => {}) => {
  axios
    .get(url, {
      params: data
    })
    .then(resp => {
      if (resp) {
        success && success(resp)
      } else {
        failure && failure('请求失败')
      }
    })
  // .catch((error) => {
  //   if (window.Raven) {
  //     window.Raven.captureException(error)
  //   }
  //   failure && failure('网络不给力,请稍后再试')
  // })
}

const post = (url, data = {}, success = () => {}, failure = () => {}) => {
  let params = new FormData()
  for (var key in data) {
    params.append(key, data[key])
  }
  axios.post(url, params).then(resp => {
    if (resp) {
      success && success(resp)
    } else {
      failure && failure('请求失败')
    }
  })
  // .catch((error) => {
  //   if (window.Raven) {
  //     window.Raven.captureException(error)
  //   }
  //   failure && failure('网络不给力,请稍后再试')
  // })
}
...

原因分析

post请求失败

axios-config.js配置文件对post 封装时传入的参数被进行了new FormData的处理

get请求失败

mock接收不到get请求的参数

解决方案

post请求失败

去掉axios-config.js配置文件对new FormData的处理

const post = (url, data = {}, success = () => {}, failure = () => {}) => {
  let params = data
  axios.post(url, params).then(resp => {
    if (resp) {
      success && success(resp)
    } else {
      failure && failure('请求失败')
    }
  })
  // .catch((error) => {
  //   if (window.Raven) {
  //     window.Raven.captureException(error)
  //   }
  //   failure && failure('网络不给力,请稍后再试')
  // })
}

get请求失败

请求改为正则,然后从opt.url中可拿到参数

Mock.mock(/\/gettest*?/, 'get', opt => {
  console.log(opt)
  return {a: '111'}
})

console.log(opt)

{url: "/gettest?test=1", type: "GET", body: null}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值