diff options
| author | Ibrahim Mkusa <ibrahimmkusa@gmail.com> | 2023-05-04 21:36:29 -0400 | 
|---|---|---|
| committer | Ibrahim Mkusa <ibrahimmkusa@gmail.com> | 2023-05-04 21:36:29 -0400 | 
| commit | d49ab50cbfc7e11a9a080d82eed5dc23228ac384 (patch) | |
| tree | 025a5529e3b16141683a41f16b2968dd1afb3c87 | |
| parent | 64dfcb8c4a4c9fc4dfaa6b7e4e8c2971461a4f04 (diff) | |
wrap up demonstation on HTTP POST, express and Postman
| -rw-r--r-- | practice/index.js | 30 | 
1 files changed, 30 insertions, 0 deletions
| diff --git a/practice/index.js b/practice/index.js index f6f51a5..1f457b0 100644 --- a/practice/index.js +++ b/practice/index.js @@ -1,6 +1,7 @@  const express = require('express')  const app = express() +app.use(express.json())  let notes = [    {      id: 1, @@ -19,6 +20,7 @@ let notes = [    }  ] +  app.get('/', (request, response) => {    response.send('<h1>Habari Tanzania</h1>')  }) @@ -48,6 +50,34 @@ app.delete('/api/notes/:id', (request, response) => {    response.status(204).end()  }) +const generateId = () => { +  const maxId = notes.length > 0 +    ? Math.max(...notes.map(n => n.id)) +    : 0 +  return maxId + 1 +} + +app.post('/api/notes', (request, response) => { +  const body = request.body + +  if (!body.content) { +    return reponse.status(400).json({ +      error: 'content missing' +    }) +  } + +  const note = { +    content: body.content, +    important: body.important || false, +    id: generateId(), +  } + +  notes = notes.concat(note) + +  console.log(note) +  response.json(note) +}) +  const PORT = 3001  app.listen(PORT)  console.log(`Server running on port ${PORT}`) | 
