首页 > 解决方案 > 创建一个待办事项列表应用程序并停留在帖子上

问题描述

我不想要答案,而是想要一个正确方向的点,因为这是我的期末考试或起点。这就是给予的东西,我只需要填写其余部分。我们也不能使用本地存储来保存用户输入

// POST handler adds a task to a list
app.post('/task', (req, res) => {
res.set('Content-Type', 'application/json');

/*
    Input: data coming into this handler will be in the form:

    {"task": "mytask"}

    You can see contents of the incoming request with:
    console.log(req.body.task). "req" is the request
    and within it, the property req.body holds the incoming data
    above from the client request, hence "task" is a property of
    that incoming request data object.

    Output: This handler should send the datastore back to
    the client with a 201 response code if successful, and return
    and 400 response code with no response body if the task already
    exists in either the TODO or Completed list.
*/


console.log(req.body.task);

/*
    YOUR CODE HERE
*/

// send 201 status with no response body
res.status(201).send({})
});

我打开了几个选项卡,其中包含有关节点和帖子的不同文章,但也许​​只是我不明白这个概念。

这是我的数据存储

let taskDatastore = {
"todo": [
    "finish test 2",
],
"completed": [
    "read the test instructions",
],
};

标签: javascriptexpresspost

解决方案


首先从请求正文中提取任务,然后检查待办事项已完成数组是否包含此任务,并在响应中发送相应的状态码。

// POST handler adds a task to a list
app.post('/task', (req, res) => {
  res.set('Content-Type', 'application/json');

  /*
      Input: data coming into this handler will be in the form:

      {"task": "mytask"}

      You can see contents of the incoming request with:
      console.log(req.body.task). "req" is the request
      and within it, the property req.body holds the incoming data
      above from the client request, hence "task" is a property of
      that incoming request data object.

      Output: This handler should send the datastore back to
      the client with a 201 response code if successful, and return
      and 400 response code with no response body if the task already
      exists in either the TODO or Completed list.
  */


  let taskDatastore = {
    "todo": [
      "finish test 2",
    ],
    "completed": [
      "read the test instructions",
    ],
  };

  const task = req.body.task;

  // Check if task already exists in the TODO or COMPLETED arrays
  if (taskDatastore.todo.includes(task) || taskDatastore.completed.includes(task)) {
    // send 400 status with no response body
    res.status(400).send({});
  } else {
    // send 201 status with datastore in response body
    res.status(201).send(taskDatastore);
  }
});


推荐阅读