Express

Express.js - Library for Routing Web Requests to Handler

Express.js is a JavaScript library that simplifies the process of registering endpoints with the web server so that the requests from your JavaScript code on the client are routed to the correct code within the Web API.

Basic Web Server

const express = require('express');

const app = express();

app.get('/', (req, res)=> {
  res.send('Hello World!');

  // req: HTTP request:
  // URL parameters, query string, data in 
  // request body

  // res: HTTP response: what you send back to the client
  // JSON data, render a template, redirect, etc.
})

const port = 3000;
app.listen(port, ()=> {
  console.log(`Server started on port ${port}`)
});

Testing Web API - VS Code Rest Client Extension

This is a great extension that allows you to execute web APIs within VS Code.

Create a file named server.rest at the top level of your project. A "Send Request" will appear above the GET command. Click it to execute the request and an output window will show the results.

Install JSON Viewer

install nodemon

nodemon auto-detects changes to the source files in the project and automatically restarts the server. Use the "-D" option to install it as a dev dependency, so it won't be included in the production modules.

Create a script to launch server in package.json

Now, when we enter the command "npm run dev" it will launch server.js with nodemon.

And when we modify the source code, we just need to refresh the web browser instead of restarting the node server.

Static Files - public folder

Create a folder named public at the top-level of your project and express will automatically serve requests for static files in that folder. HTML and CSS are examples of files that would go here.

Express Basic Request Handling

Create a folder named data and add a new file named zoo.js with the following data.

Express Middleware

Express Routes

Express routes allow you to move your handlers into separate files. Create a new directory named "routes" and create a file named "animals.js" within it. Move the following code to the new files.

routes/animals.js

npm i uuid to generate unique ids

Resources

Last updated

Was this helpful?