Express-在发布请求后推送到测试阵列

时间:2018-12-10 12:48:58

标签: javascript node.js json express

我在Express中创建CRUD操作,我想在同一文件中的简单数组上对此进行测试。我的问题是,一切正常,但删除或发布请求不会更新该阵列的项目。我在做什么错了?

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
app.use(cors());

app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
let cats = [
  {
    id: 1,
    title: "Filemon",
    color: "black"
  },
  {
    id: 2,
    title: "Burys",
    color: "fire"
  },
  {
    id: 3,
    title: "Mysia",
    color: "Grey"
  },
  {
    id: 4,
    title: "Niunia",
    color: "Black - grey"
  }
];
app.get("/api/cats", (req, res) => {
  res.send(cats);
});
app.get("/api/cats/:id", (req, res) => {
  res.send(cats.find(t => t.id === parseInt(req.params.id)));
});

app.post("/api/cats", (req, res) => {
  let cat = {
    id: cats[cats.length - 1].id + 1,
    title: req.body.title
  };
  cats.push(req.body);
  res.send(cat);
});

我想添加带有动态ID的猫,具体取决于最后一只猫的ID。当我添加一只猫时,其ID为 5 ,但是当我添加猫时,其ID为未定义,因为我的数组未更新。如何解决呢?

1 个答案:

答案 0 :(得分:1)

app.post("/api/cats", (req, res) => {
  let cat = {
    id: cats[cats.length - 1].id + 1,
    title: req.body.title
  };
  cats.push(req.body);
  res.send(cat);
});

cats.push(req.body);应该读为cats.push(cat); 您需要将新对象推入cats数组。但是,这不是永久的,只要您重新启动服务器,数据就会恢复为初始cats声明中列出的数据。对于永久数据,您需要将此信息存储在数据库中。