简体   繁体   English

POST 请求到 PUT 请求

[英]POST Request to PUT Request

" An open source course that I am taking has the following prompt for fullstack development: 3.17 : Phonebook database, step5 If the user tries to create a new phonebook entry for a person whose name is already in the phonebook, the frontend will try to update the phone number of the existing entry by making an HTTP PUT request to the entry's unique URL. Modify the backend to support this request. Verify that the frontend works after making your changes." " 我正在参加的一门开源课程对全栈开发有以下提示: 3.17 : Phonebook database, step5 如果用户尝试为姓名已经在电话簿中的人创建新的电话簿条目,前端将尝试更新通过向条目的唯一 URL 发出 HTTP PUT 请求来获取现有条目的电话号码。修改后端以支持此请求。在进行更改后验证前端是否正常工作。” * *

It appears that this would call for an express app.put request called inside on an app.post request.这似乎需要在 app.post 请求中调用一个快速的 app.put 请求。 Is there something that I'm missing here?有什么我在这里想念的吗? How you handle this kind of logic with mongoDB/mongoose/expresss?你如何用 mongoDB/mongoose/expresss 处理这种逻辑? My current post code is pasted below.我当前的邮政编码粘贴在下面。

Thanks谢谢

app.post('/api/persons',(req,res) => {
  const body = req.body
  const containsNameNumber = body.name && body.number

  if(!containsNameNumber){
    return res.status(400).json({
      error:"must specify a name and a number"
    })
  }

  const phone = new Person({
    name: body.name,
    number:body.number
  })

  phone.save().then(savedPerson => {
      res.json(savedPerson)
    })
})

I think you are missunderstanding one thing, check PUT definition from RFC7231我认为您误解了一件事,请检查RFC7231 中的PUT定义

The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload PUT方法请求创建目标资源的状态或替换为由包含在请求消息有效负载中的表示定义的状态

Is importante the part "be created".重要的是“创建”部分。 So with a PUT if the resource exists it will be updated but if not exists will be created.因此,对于PUT如果资源存在,它将被更新,但如果不存在,则将被创建。

If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response.如果目标资源没有当前的表示并且PUT成功创建了一个,那么源服务器必须通过发送201 (Created)响应来通知用户代理。

So you only have to do a PUT call and check if exists to update (return 200 Ok ) or not exists to create (return 201 Created ).所以你只需要做一个PUT调用并检查是否存在更新(返回200 Ok )或不存在创建(返回201 Created )。

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

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