Week 09

We're continuing our discussion about backends with Express.js.

As mentioned in Week 06, different HTTP verbs correspond to CRUD (Create, Read, Update, Delete) operations. So far, we've covered the Create and Read operations using POST and GET. Now, we will implement the Delete and Update operations.

For Delete and Update operations, you typically want to modify or remove a single record. Since the record must already exist, we need a way to uniquely identify it. More often than not, this is done using an identifier. In the phonebook example, the identifier we used for each record was the phone number.

As mentioned in Week 06, we send the identifier in the URL. The most common way of sending identifiers is through query string parameters. These are key-value pairs added to a URL after a ?, providing extra information to the server. Multiple parameters are separated by &. Exampe: https://example.com/users?id=123&lang=en.

Accessing Query String Parameters in Express.js

In Express.js, each route has access to the request, including its body and query string parameters. If you store the request in an argument named req, req.query will give you the query string parameters of the request. This property is an object containing a key for each query string parameter in the route. Read more here.

Example: If the URL is https://example.com/users?id=123&lang=en, req.query will be:

{ id: '123', lang: 'en' }

You can test this by adding a delete route and logging the query string parameters of the request:

app.delete('/contacts', (req, res) => { console.log(req.query) })

Deleting a Key from an Object

We need to be able to delete a key from an object for the phonebook project. Since we used an object, we can use the delete operator to remove a key from the phonebook. Example (from Mozilla):

const Employee = { firstname: "Maria", lastname: "Sanchez", }; delete Employee.firstname; console.log(Employee.firstname); // Expected output: undefined