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

点击Add按钮后新增Todo不显示且POST请求报404问题求助

问题分析与解决方案

1. 404错误的根源:请求头拼写错误

你的POST请求里的Content-Type存在拼写错误,把application/json写成了appication/json(少了字母l),这会导致dummyjson的接口无法正确识别请求格式,从而返回404。

修正代码(store的action部分):

const res = await fetch('https://dummyjson.com/todos/add', {
    method: 'POST',
    headers: {
      // 修正拼写错误
      'Content-Type': 'application/json;charset=utf-8',
    },
    body: JSON.stringify(data),
});

2. 页面不显示新任务的原因

因为接口返回res.ok为false,所以没有执行context.commit('addnewTask', result),导致store里的tasks数组没有更新,页面自然看不到新任务。虽然你在组件里生成了newTask对象,但只有当action里的commit执行后,state才会变化,页面的computed属性才会同步更新。

3. 额外优化建议

  • 补全action定义:确保action函数正确接收context和data参数:
const actions = {
  async addTask(context, data) {
    // 这里是请求代码
  }
}
  • 避免空任务提交:组件里的addTask方法,修改判断条件来检查输入内容是否为空:
addTask() {
  let newTask = {
    id: Math.floor(Math.random() * 25 + 200),
    todo: this.todo.trim(),
    completed: false,
  };
  // 仅在todo内容不为空时提交
  if (newTask.todo) {
    this.$store.dispatch('addTask', newTask);
    // 提交后清空输入框
    this.todo = '';
  }
},
  • 确认state初始值:确保store的state里tasks是一个数组,比如:
export const state = () => ({
  tasks: []
})

验证效果

修正后,点击Add按钮,POST请求会正常返回,action会执行commit,通过unshift把新任务添加到tasks数组顶部,页面的v-for会自动渲染出新任务。

内容的提问来源于stack exchange,提问作者user21728832

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:22:22