简体   繁体   English

Node Express.js从JSON数据中删除条目

[英]Node Express.js deleting an entry from json data

I am trying to delete an entry from json data. 我正在尝试从json数据中删除一个条目。

This is what I do to view the data: 这是我要查看的数据:

app.route('/data/:id')
    .get((req:Request, res: Response) => {
    let id = req.params.id;
    res.status(200).send(projects[id]);
});

And that will show the data with that id in the json data. 这将在json数据中显示具有该id的数据。

This is what I've got to delete: 这是我要删除的内容:

app.route('/data/delete/:id')
    .delete((req:Request, res: Response) => {
    let id = req.params.id;
    res.status(200).send(projects[id]);
});

What I'm I doing wrong, missing from the delete code above? 我做错了什么,缺少上面的删除代码?

使用delete关键字并返回响应

delete projects[id]

You've created a delete route containing the code which will run when an HTTP client asks your HTTP server to delete something matching the URL. 您已经创建了一个delete 路由,其中包含当HTTP客户端要求HTTP服务器删除与URL匹配的内容时将运行的代码。

The code you've written inside it gets the id, then sends it from the projects object. 您在其中编写的代码将获取ID,然后从projects对象发送该ID。

So what you are missing is code which actually deletes anything. 因此,您缺少的是实际上删除任何内容的代码。


You can use the delete keyword to do this. 您可以使用delete关键字执行此操作。

let id = req.params.id;
delete projects[id];

You probably shouldn't return data you just deleted though. 不过,您可能不应该返回刚删除的数据。 You can send a 204 No Content response instead. 您可以改为发送204 No Content响应。

res.status(204).send()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM