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