NodeJS 更新和删除的 URL 参数或请求体参数

huangapple go评论70阅读模式
英文:

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
});

huangapple
  • 本文由 发表于 2023年7月6日 11:21:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定