Tutorial 08

Build the Phone Book web app we covered in Week 08. You need to build both the front-end and back-end.


Add Contact:


List Contacts:



Solution

new_contact.js:

const init = async function () { const formEl = document.querySelector("#form") formEl.addEventListener("submit", async (event) => { event.preventDefault() // grab the data from the form const data = new FormData(formEl) const objectData = Object.fromEntries(data) // backend must be running already const res = await fetch("http://localhost:3000/contacts", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(objectData), }) }) } init()

contacts.js:

const init = async function () { const gridEl = document.querySelector("div.grid") // backend must be running already const res = await fetch("http://localhost:3000/contacts") const data = await res.json() const keys = Object.keys(data) console.log(keys) keys.forEach((objectKey) => { const phoneNumber = objectKey const name = data[objectKey] const cellEl = document.createElement("div") cellEl.classList.add("cell") // <div class="cell"></div> const innerH = ` <div class="card"> <div class="card-content"> <div class="content"> <div class="title">${name}</div> <p class="subtitle">${phoneNumber}</p> <button class="button is-small is-danger has-text-white">Delete</button> </div> </div> </div> ` cellEl.innerHTML = innerH gridEl.append(cellEl) }) } init()

index.js (backend)

const express = require('express') // import express const app = express() // initializing express const cors = require('cors') // importing cors const port = 3000 // the port that the web server will run on const phoneBook = { } // this will allow ALL origins to use this backend app.use(cors()) app.use(express.json()); // to get ALL contacts app.get('/contacts', (req, res) => { console.log("GET /contact was called") res.send(phoneBook) }) // to create a contact app.post('/contacts', (req, res) => { phoneBook[req.body.phone_number] = req.body.name console.log(phoneBook) res.send(phoneBook) }) app.listen(port, () => { console.log(`Example app listening on port ${port}`) })