You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 08:45:32