From d49ab50cbfc7e11a9a080d82eed5dc23228ac384 Mon Sep 17 00:00:00 2001 From: Ibrahim Mkusa Date: Thu, 4 May 2023 21:36:29 -0400 Subject: wrap up demonstation on HTTP POST, express and Postman --- practice/index.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) 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('

Habari Tanzania

') }) @@ -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}`) -- cgit v1.2.3