Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

138
Views
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."*

It appears that this would call for an express app.put request called inside on an app.post request. Is there something that I'm missing here? How you handle this kind of logic with 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)
    })
})
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

I think you are missunderstanding one thing, check PUT definition from RFC7231

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

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.

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.

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).

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs