Creating a 10-Step Node API with Express.js

ByThiago Adriano in

For those who do not know Express.js, it is an excellent Node.js framework that helps us build our Web applications. It is a very simple framework to use, so it is being adopted by developers of all levels. So we can get to know it a little bit more, let’s take 10 steps down to create a Web Site.

1. Premises

For this article, we will not cover the installation of Node.js. We will start from a machine with it already installed and configured. Create a new directory on your computer and create a new folder – we will use node-express, but you can choose another name of your choice. After that, run the command below to download our module.

npm install express

2.  Setting

Now, we need to create our package.json file. This is our start point file of our Node projects. To do this, run the command below. It will create our file with the module express reference.

npm init -y

3. Structure of our project

Create a structure of folders and files as it is in the image below:

4. Creating Server File

Let’s now create the initialization file of our project. For anyone coming from the PHP world, it would be our index.php or HomeController.cs in the .NET MVC. To do this, open your server.js file and paste the code below on it:

const app = require('../src/app');
const port = normalizaPort(process.env.PORT || '3000');
function normalizaPort(val) {
    const port = parseInt(val, 10);
    if (isNaN(port)) {
        return val;
    }
if (port >= 0) {
        return port;
    }
return false;
}
app.listen(port, function () {
    console.log(`app listening on port ${port}`)
})

In the above code, we are importing a module that we will create in the next steps. Then we are setting a port for it to run, in the end we are passing to the app.listen method, the port that we want it to listen to our project and a console.log with it.

5.  Controller

In order for us to organize our code, we split it thinking about an MVC pattern. In the code below, we have our Actions from our Controllers.

exports.post = (req, res, next) => {
    res.status(201).send('Requisição recebida com sucesso!');
};
exports.put = (req, res, next) => {
    let id = req.params.id;
    res.status(201).send(`Requisição recebida com sucesso! ${id}`);
};
exports.delete = (req, res, next) => {
    let id = req.params.id;
    res.status(200).send(`Requisição recebida com sucesso! ${id}`);
};

6. Routes

Now, let’s create our routes. In this part, we have two files: index.js and personRoute.js. The index.js file would be to pass the version that is in our API or so we can move to a balancer (Load Balancer) to check if our API is up. The personRoute.js contains the routes that we will use for our PersonController.

Index.js:

const express = require('express');
const router = express.Router();
router.get('/', function (req, res, next) {
    res.status(200).send({
        title: "Node Express API",
        version: "0.0.1"
    });
});
module.exports = router;

PersonRoute

const express = require('express');
const router = express.Router();
const controller = require('../controllers/personController')
router.post('/', controller.post);
router.put('/:id', controller.put);
router.delete('/:id', controller.delete);
module.exports = router;

7. Settings

The app.js file is responsible for the settings of our project. It is in that, that we must configure our database, routes etc. Thinking back to the .NET world, I would dare say it would be our web.config.

const express = require('express');
const app = express();
const router = express.Router();
//Rotas
const index = require('./routes/index');
const personRoute = require('./routes/personRoute');
app.use('/', index);
app.use('/persons', personRoute);
module.exports = app;const express = require('express');
const app = express();
const router = express.Router();
//Rotas
const index = require('./routes/index');
const personRoute = require('./routes/personRoute');
app.use('/', index);
app.use('/persons', personRoute);
module.exports = app;

8. Nodemon

The nodemon package assists us at the time of our development. With it, we do not need to stop and up out our APP again. It checks that a change has occurred and refreshes automatically. To install it, run the command below on your console:

npm install -g nodemon

9. Package.config file

This would be the initial file in Node projects, in it we have all dependencies:

{
  "name": "node-express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "express": "^4.15.4"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon ./bin/server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

10. Tests

In order for us to test our project, enter the npm install command on your console to import the packages needed for our application. As soon as it finishes, run the command npm start. If everything is OK in the previous steps, you will see the message below in your console:

Now open in your browser the address http: // localhost: 3000 /. It should display the following message as a return of our route Index:

Follow the link to the complete project we created in this Github article.

Leave a comment! 0

read more