Implementing a simple REST server with Express

While Express has a powerful templating system, making it suitable for delivering HTML web pages to browsers, it can also be used to implement a simple REST service. The parameterized URLs we showed earlier (/user/profile/:id) can act like parameters to a REST call. And Express makes it easy to return data encoded in JSON.

Now, create a file named fiboserver.js containing this code:

const math = require('./math'); const express = require('express'); const logger = require('morgan'); const app = express(); app.use(logger('dev')); app.get('/fibonacci/:n', (req, res, next) => { math.fibonacciAsync(Math.floor(req.params.n), (err, val) => { if (err) next('FIBO SERVER ERROR ' + err); else res.send({ ...

Get Node.js Web Development - Fourth Edition 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.