Vue.js+Django中axios POST请求状态码200却触发catch错误
问题排查:Axios返回200响应却触发Catch回调,成功/失败弹窗同时弹出
核心原因:Then回调内的语法错误
你的代码中,then回调里存在一处明显的语法错误:
this.this.me = res.data;
这里多写了一个this,正确写法应为:
this.me = res.data;
这个错误会导致then块执行到该行时抛出异常,进而触发catch回调。所以流程会先执行this.dialogClose.success = true弹出成功弹窗,随后因语法错误进入catch设置dialogClose.fail = true,最终两个弹窗同时出现。
额外优化与排查建议
表单获取方式优化:
当前用原生DOM查询document.getElementById("login-from")获取表单,建议改用Vue的ref属性,更符合组件化开发规范:const postData = new FormData(this.$refs.loginForm);同时注意你的表单ID是
login-from(拼写为from而非form),建议修正为login-form避免混淆。Django响应格式验证:
虽然状态码为200,但需确认后端返回的是合法JSON格式。如果响应内容解析失败,Axios也会触发catch回调。可在then中打印res.data的类型与内容,验证解析是否正常。Axios配置抽离:
你在组件内直接配置Axios全局参数,建议将配置抽离到单独文件(如axios.js),避免重复配置,方便统一管理。
修正后的关键代码片段
methods: { save() { console.log("save()..."); const postData = new FormData(this.$refs.loginForm); axios .post("/api/login/", postData) .then((res) => { console.log("LOGIN POST RES", res); this.dialogClose.success = true; this.me = res.data; }) .catch((err) => { console.log("LOGIN POST ERR.RESPONSE", err.response); this.dialogClose.fail = true; }); }, },
内容的提问来源于stack exchange,提问作者KIHA
相关产品推荐
相关产品推荐

