Simple API Server
This chapter explains how to create a simple Node.js API server using the Express.js framework.
First, install the dependencies.
$ npm install --save [email protected]
Router
Create a new file ./src/router/index.js
and define a router.
const express = require('express');
const usersRoutes = require('./users');
exports.createRouter = function () {
const router = express.Router({
mergeParams: true
});
router.get('/users', usersRoutes.index);
router.get('/users/:id', usersRoutes.show);
return router;
};
Routes
Create a new routes file ./src/router/users.js
which will expose user-related actions.
exports.index = function (req, res) {
res.send('list of users');
};
exports.show = function (req, res) {
let id = req.params.id;
res.send(`user with ID${id}`);
};
Server
Open the ./src/index.js
file and paste the content below.
const express = require('express');
const {createRouter} = require('./router');
exports.Server = class {
constructor(config) {
this._config = config;
this._app = null;
this._server = null;
}
listen() {
return new Promise((resolve) => {
if (this._server) return this;
this._app = express();
this._app.use('/', createRouter());
let {port, host} = this._config;
this._server = this._app.listen(port, host, resolve);
});
}
close() {
return new Promise((resolve) => {
if (!this._server) return this;
this._server.close(resolve);
this._server = null;
this._app = null;
});
}
}
Configuration
Open the ./package.json
file and set configuration variables and a start script.
{
"config": {
"server": {
"port": 4444,
"host": "127.0.0.1"
}
},
"scripts": {
"start": "node ./src/scripts/start.js"
}
}
Create a new configuration file ./src/config.js
and set application variables.
exports.serverConfig = {
port: process.env.npm_package_config_server_port,
host: process.env.npm_package_config_server_host
};
Create a startup script ./src/scripts/start.js
which start the application.
const {Server} = require('..');
const {serverConfig} = require('../config');
const app = new Server(serverConfig);
app.listen().then(() => {
console.log('Server started');
}).catch((error) => {
app.close();
console.log('Error', error);
});
Run the npm start
command to start the server then navigate to http://localhost:4444/users
to see the result. Use npm config command to configure the server.