How to do it...

Build a simple RESTful API server that will have two endpoints or answer to paths /time and /date when a GET request is made. However, on /date path, we will pretend that there is an internal error and make the request fail in order to see how to handle errors in asynchronous requests as well:

  1. Create a new file named api-server.js
  2. Include the ExpressJS library and initialize a new ExpressJS application:
      const express = require('express') 
      const app = express() 
  1. For /time path, simulates a delay of 2s before sending a response:
      app.get('/time', (req, res) => { 
          setTimeout(() => { 
              res.send(new Date().toTimeString()) 
          }, 2000) 
      }) 
  1. For /date path, simulates a delay of 2s before sending a failed response:
 app.get('/date', ...

Get MERN Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.