Vue模板无法显示后端返回的成功消息问题求助
解决Vue模板无法显示后端返回成功消息的问题
问题根源
- 数据取值路径错误:后端返回的JSON结构是外层
data字段嵌套包含message的对象,你当前代码里取的response.data.message找不到对应值,正确路径应为response.data.data.message。 - async/await与then混用导致逻辑混乱:在async函数中同时使用await和then链式调用,会导致
const response接收的是then回调的返回值(此处为undefined),同时混淆了异步数据的处理逻辑。
修复方案
方案一:统一使用async/await + try/catch(推荐)
修改handleSubmit方法,去掉then/catch,改用try/catch处理异步请求:
async handleSubmit() { try { const response = await axios.post("http://localhost:5000/api/auth/forgotPassword", { email: this.email }); // 修正数据取值路径 this.message = response.data.data.message; console.log(response); } catch (err) { console.log(err); } }
方案二:保留then/catch写法(去掉await)
如果习惯用then/catch风格,移除async和await,避免混用语法:
handleSubmit() { axios.post("http://localhost:5000/api/auth/forgotPassword", { email: this.email }) .then(response => { // 修正数据取值路径 this.message = response.data.data.message; console.log(response); }) .catch(err => console.log(err)); }
验证步骤
- 按上述方式修改代码后触发请求。
- 打开浏览器控制台,查看
response打印结果,确认response.data.data.message存在且值正确。 - 此时模板中的
{{ message }}即可正常显示后端返回的成功消息。
内容的提问来源于stack exchange,提问作者chunfee
相关产品推荐
相关产品推荐

