gpt4 book ai didi

javascript - Express - 根据发布请求推送到测试数组

转载 作者:行者123 更新时间:2023-12-03 00:34:50 26 4
gpt4 key购买 nike

我正在 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 是未定义,因为我的数组未更新。如何解决这个问题?

最佳答案

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 声明中所规定的状态。对于永久数据,您需要将此信息存储在数据库中。

关于javascript - Express - 根据发布请求推送到测试数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53706002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com