【问题标题】:I'm trying to create a put request and delete request with a complicated array我正在尝试使用复杂的数组创建一个放置请求和删除请求
【发布时间】:2020-11-24 20:14:03
【问题描述】:

我正在尝试创建一个 put 请求并删除,但我不知道如何处理 DUMMY-PLACES。我将从开头(id、内容)获取,默认情况下完成的是 false(它是dummy DB ) 例如 (6,test6) 当然这是 byIds 中的数字需要相同“6”

const express = require("express");

const router = express.Router();

const DUMMY_PLACES = [
  {
    todos: {
      allIds: [1, 2, 3, 4],
      byIds: {
        "1": {
          content: "test1",
          completed: false,
        },
        "2": {
          content: "test2",
          completed: false,
        },
        "3": {
          content: "test3\\",
          completed: false,
        },
        "4": {
          content: "test4",
          completed: false,
        },
      },
    },
    visibilityFilter: "all",
  },
];

router.get("/todos", (req, res, next) => {
  try {
    const place = DUMMY_PLACES;
    console.log(place);
    res.json({ place });
  } catch (err) {
    next({ status: 400, message: "failed to get todos" });
  }
  // => { place } => { place: place }
});

router.put("/todos/", async (req, res, next) => {
  const { id, content } = req.body;
  try {
    todo = DUMMY_PLACES;
    console.log(todo.todos);
  } catch (err) {
    next({ status: 400, message: "failed to update todo" });
  }
});

module.exports = router;

【问题讨论】:

    标签: javascript node.js arrays loops request


    【解决方案1】:

    要编辑单个待办事项,首先检查它是否确实存在并相应更新。

    router.put("/todos", async (req, res, next) => {
      const { id, content } = req.body;
      // Check if todo actually exists
      const todoExists = DUMMY_PLACES[0].todos.byIds.hasOwnProperty(id);
      if (!todoExists) {
        next({ status: 400, message: `todo with id ${id} does not exist` });
      }
      // Update todo
      DUMMY_PLACES[0].todos.byIds[id].content = content;
      res.sendStatus(200);  
    });
    

    要删除待办事项,请从 byIds 对象中删除键

    router.put("/todos", async (req, res, next) => {
      const { id } = req.body;
      delete DUMMY_PLACES[0].todos.byIds[id];
      res.sendStatus(200);  
    });
    

    【讨论】:

    • 谢谢,这对我映射它很有帮助。反响很好。
    • 您知道如何在 byIds 中添加新的待办事项吗?
    • @Ethanolle 添加 POST 路由并将新的 todo 添加到 byIds 对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多