Skip to content

Instantly share code, notes, and snippets.

@Nalini1998
Created July 19, 2023 09:29
Show Gist options
  • Save Nalini1998/43ef8d86df038a9bcaa0c30ce1b10ae0 to your computer and use it in GitHub Desktop.
Save Nalini1998/43ef8d86df038a9bcaa0c30ce1b10ae0 to your computer and use it in GitHub Desktop.
Express allows us to set the status code on responses before they are sent. Response codes provide information to clients about how their requests were handled. Until now, we have been allowing the Express server to set status codes for us. For example, any `res.send()` has by default sent a `200 OK` status code. The res object has a `.status()`…
LEARN EXPRESS ROUTES
Setting Status Codes
Express allows us to set the status code on responses before they are sent. Response codes provide information to clients about how their requests were handled.
Until now, we have been allowing the Express server to set status codes for us. For example, any res.send() has by default sent a 200 OK status code.
The res object has a .status() method to allow us to set the status code, and other methods like .send() can be chained from it.
const monsterStoreInventory = { fenrirs: 4, banshees: 1, jerseyDevils: 4, krakens: 3 };
app.get('/monsters-inventory/:name', (req, res, next) => {
const monsterInventory = monsterStoreInventory[req.params.name];
if (monsterInventory) {
res.send(monsterInventory);
} else {
res.status(404).send('Monster not found');
}
});
In this example, we've implemented a route to retrieve inventory levels from a Monster Store. Inventory levels are kept in the monsterStoreInventory variable. When a request arrives for /monsters-inventory/mothMen, the route matches and so the callback is invoked. req.params.name will be equal to 'mothMen' and so our program accesses monsterStoreInventory['mothMen']. Since there are no mothMen in our inventory, res.status() sets a 404 status code on the response, and .send() sends the response.
Instructions
Let’s make sure that our GET /expressions/:id route
Let’s make sure that our GET /expressions/:id route handles invalid requests properly, for instance if we request an expression ID that does not exist.
Complete our route so that it sends back the correct expression object if it exists and sends back a 404 response if it does not.
This Project was completed by Nalini Vo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment