英文:
NodeJS url param or body param for update and delete
问题
URL 参数:
// 更新待办事项
app.put('/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const newTodoContent = req.body.todo;
// 代码的其余部分
});
请求体:
// 更新待办事项
app.put('/todos', (req, res) => {
const id = parseInt(req.body.id);
const newTodoContent = req.body.todo;
// 代码的其余部分
});
我可以使两种方式都起作用。哪种方式被推荐?在代码效率或安全性方面是否有区别?根据我的研究,URL 参数更常见,但将 ID 传递到请求体中似乎更加优雅。
英文:
I'm creating an API in NodeJS and am not sure whether to update and delete items based on an ID passed in the URL or request body.
URL parameter:
// Update a todo
app.put('/todos', (req, res) => {
const id = parseInt(req.params.id);
const newTodoContent = req.body.todo;
// rest of the code
});
Request body:
// Update a todo
app.put('/todos', (req, res) => {
const id = parseInt(req.body.id);
const newTodoContent = req.body.todo;
// rest of the code
});
I can make both work. Which would be the recommended way? Is there any difference in code efficiency or security? Based on my research the URL parameter is more common but it seems more elegant passing the id in the request body.
答案1
得分: 1
首选方法是将元素的ID作为URL参数传递,如下所示:
app.put('/todos/:todoId', (req, res) => {
// 代码的其余部分
});
英文:
Preferred way is to pass the id of the element in the url as params as follows
> app.put('/todos/:todoId', (req, res) => {
// rest of the code
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论