问题描述
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}