• 10 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 2/21/22

Create an Express App

Writing web servers in pure Node is possible but time-consuming and detailed, as you have to parse every incoming request manually. Using the Express framework makes these tasks much simpler, allowing you to build out your APIs in half the time. Let's install it now.

Install Express

To add Express to your project, run the following from within your  backend  folder:

npm install express

Create a new  app.js  file that will contain your Express app:

const express = require('express');

const app = express();



module.exports = app;

Run the Express App on the Node Server

Go back to your  server.js  file, and modify it as follows:

const http = require('http');
const app = require('./app');

app.set('port', process.env.PORT || 3000);
const server = http.createServer(app);

server.listen(process.env.PORT || 3000);

Making a request to this server will throw an Express-generated 404 error, as the Express app has no way of responding yet. You'll want to set up a simple response to make sure everything is working properly by making an addition to the  app.js  file:

const express = require('express');

const app = express();

app.use((req, res) => {
   res.json({ message: 'Your request was successful!' }); 
});

module.exports = app;

If you try and make a request to your server, you should get back a JSON object containing the specified message.

Now that your Node server is correctly serving up the Express app let's see how you can add functionality to that app.

Add Some Middleware

An Express app is a series of functions called middleware. Each piece of middleware receives the request and response objects and can read, parse, and manipulate them as necessary. Express middleware also gets the following method, which allows that middleware to pass execution on to the next piece. Let's see how all of that works.

const express = require('express');

const app = express();

app.use((req, res, next) => {
  console.log('Request received!');
  next();
});

app.use((req, res, next) => {
  res.status(201);
  next();
});

app.use((req, res, next) => {
  res.json({ message: 'Your request was successful!' });
  next();
});

app.use((req, res, next) => {
  console.log('Response sent successfully!');
});

module.exports = app;

This Express app contains four pieces of middleware:

  • The first logs "Request received" to the console and passes on execution.

  • The second adds a 201 status code to the response and passes on execution.

  • The third sends the JSON response and passes on execution.

  • The final piece of middleware logs "Response sent successfully" to the console.

This very simple server doesn't do much for now; however, it illustrates how middleware works in an Express app.

Improve server.js

Before moving on, let's make a few improvements to the  server.js  file, which will make it more stable and suitable for deployment:

const http = require('http');
const app = require('./app');

const normalizePort = val => {
  const port = parseInt(val, 10);

  if (isNaN(port)) {
    return val;
  }
  if (port >= 0) {
    return port;
  }
  return false;
};
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

const errorHandler = error => {
  if (error.syscall !== 'listen') {
    throw error;
  }
  const address = server.address();
  const bind = typeof address === 'string' ? 'pipe ' + address : 'port: ' + port;
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges.');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use.');
      process.exit(1);
      break;
    default:
      throw error;
  }
};

const server = http.createServer(app);

server.on('error', errorHandler);
server.on('listening', () => {
  const address = server.address();
  const bind = typeof address === 'string' ? 'pipe ' + address : 'port ' + port;
  console.log('Listening on ' + bind);
});

server.listen(port);

A quick run-through of what is going on here:

  • The  normalizePort  function returns a valid port, whether it is provided as a number or a string.

  • The  errorHandler  function checks for various errors and handles them appropriately — it is then registered to the server.

  • A "listening" event listener is also registered, logging the port or named pipe on which the server is running to the console.

Your Node development server is now up and running properly, and your Express app is ready to have some proper functionality added.

Let's Recap!

  • The Express framework is installed and saved to  package.json  with   npm install express  .

  • To create an Express app, simply call the  express()  method.

  • Middleware is code in your app which handles your server's requests and responses

  • Adding port normalization, error handling and basic logging to your Node server makes your app run more consistently and easier to debug.

Now that you know how to use the Express framework, we can really start creating our API. See you in the next chapter! 

Example of certificate of achievement
Example of certificate of achievement