📌  相关文章
📜  如何删除带有 id 的“api notes” - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:01:07.948000             🧑  作者: Mango

代码示例1
app.delete("/api/notes/:id", (req, res) => {
    let chosenNoteToDelete = req.params.id;
    fs.readFile(__dirname + "/db/db.json", (err, data) => {
        if (err) {
            console.log(err);
            res.sendStatus(500);
            return;
        }
        try {
            let json = JSON.parse(data);
        } catch(e) {
            console.log(err);
            res.sendStatus(500);
            return;
        }

        for (let i = 0; i < json.length; i++) {
            if (json[i].id === chosenNoteToDelete) {
                json.splice(i, 1);
                return;
            }
        }

        fs.writeFile(__dirname + "/db/db.json", JSON.stringify(json), (err) => {
            if (err) {
                console.log(err);
                res.sendStatus(500);
                return;
            }
            res.send("Successfully deleted");
        });
    });
});