axios正常返回then方法,但也走了catch方法
axios既走then方法也走catch方法可以排查是否在axios post/get 的回调里resolve(res)里是否传值为完整的res返回值。
					问题描述:
使用axios发送ajax请求,服务器返回200,数据也成功返回了,但是前台这里,axios 这边代码也走了 then方法的代码,但是走完之后,又走了catch里的代码,仔细检查了then方法里的代码,没有错误。
请求截图

axios then 和 catch 方法代码
this.login(param).then(res => { 
    if(res.data.state) {
        this.$message({
            showClose: true,
            message: '登录成功',
            type: 'success',
            duration: '1500'
        });
    } else {
        this.$message({
            showClose: true,
            message: '登录失败',
            type: 'error',
            duration: 3000
        });
    }
}).catch(err => {
    this.$message({
        showClose: true,
        message: "未找到服务器",
        type: 'warning',
        duration: 3000
    });
})
axios 请求代码
axios
  .post(url, params)
  .then(res => {
    resolve(res.data); // 错误原因其实是这里传递了res.data  正确的应该是res
  })
  .catch(err => {
    reject(err);
  });
});
错误原因分析:
1、据说 then方法里有错误代码会走catch里,没碰到过
2、我的错误原因是,post 请求里 then 方法里的 resolve(res.data)参数传递值错误
解决办法:

axios 应该是会有一套标准的返回形式

data、headers /request status statusText 这样的返回字段
axios 应该是需要判断status里的200 或者statusText里的ok 之类的,而我们只传递了 data 里的字段回去。故导致了,他既走了then,也走了catch里的代码。
版权声明
本站部分原创文章,部分文章整理自网络。如有转载的文章侵犯了您的版权,请联系站长删除处理。如果您有优质文章,欢迎发稿给我们!联系站长:
愿本站的内容能为您的学习、工作带来绵薄之力。
 
							 
						 
				 
				 
				 
				 
	 
	
评论