【axios请求mock.js失败】

【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}

猜你喜欢

转载自blog.csdn.net/lorogy/article/details/108973879
今日推荐