Posted by : at

Category : mongodb   node

This tutorial aims to guide you to the process of building API’s using Node, Express and Mongodb.

What we are Building ?

An API for Listing Songs - User can perform CRUD operations - Create, Read, Update, Delete Songs and also the Categories/Genre the Songs belongs to.

This is the part-2 of the series :

So let’s get started :D

Adding ES6 support to our Express App

In the previous tutorial we created our express app, which supports Javascript ES5 Syntax by default. But if we want to utilize the ES6 features we need to do some setup ( This step isn’t required if your project is using the latest Node version which supports ES6 syntax, you can use ES6 syntax directly. For eg. if you are using Node v.10+ ) :

So let’s configure our express app to support the latest ES6 features. We are going to use Babel - A Transpiler that converts our ES6 code to ES5.

Open up a terminal and our project using VS Code

cd myapp
code .

app.js - our app.js file

    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');
    
    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');
    
    var app = express();
    
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    
    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use('/', indexRouter);
    app.use('/users', usersRouter);
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      next(createError(404));
    });
    
    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
    
      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });
    
    module.exports = app;

So, lets now modify this file using ES6 syntax and change the user to song :

app.js

    import createError from 'http-errors';
    import express from 'express';
    import path from 'path';
    import cookieParser from 'cookie-parser';
    import logger from 'morgan';
    
    // Routes
    import indexRouter from './routes/index';
    import songsRouter from './routes/songs';
    
    // Initialize app
    const app = express();
    const port = 3000;
    
    // View engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    
    app.use(logger('combined')); 
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use('/', indexRouter);
    app.use('/songs', songsRouter);
    
    // catch 404 and forward to error handler
    app.use((req, res, next) => {
      next(createError(404));
    });
    
    // error handler
    app.use((err, req, res, next) => {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
      
      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });
    
    app.listen(port, () => {
      console.log('Listening on port' + port)
    });
    
    export default app;

So let’s try to run this app :

But we will get the error !

We will solve this problem, but let’s just change all our es5 to es6 first :

bin/www - lets change this to support es6

     #!/usr/bin/env node
    
    /**
     * Module dependencies.
     */
    
    import app from '../app';
    import debugLib from 'debug';
    import http from 'http';
    
    const debug = debugLib('myapp:server');
    
    // Rest of the code remains the same 

Also lets modify our routes,

routes/index.js:

    import express from 'express';
    const router = express.Router();
    
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { title: 'Express' });
    });
    
    exports.default = router;

and our songs routes : (rename user.js to song.js)

routes/songs.js :

    import express from 'express';
    const router = express.Router();
    
    /* GET songs listing. */
    router.get('/', (req, res, next) => {
      res.send('respond with our songs');
    });
    
    exports.default = router;

Okay, Now in order to setup es6 support, we need to install some dependencies :

We can give support of ES6 by using various approaches :

  • ES6 Support via Babel
  • ES6 Support via ESM

We will be using the easiest method the second one - ES6 support via ESM,

So install the following dependencies:

    npm install --save esm
    npm install --save-dev nodemon 

Let’s create our start script, create a new file:

start.js

    // file start.js
    require = require("esm")(module /*, options*/);
    module.exports = require("./bin/www");

Now we need to modify our package.json run scripts:

package.json (modify like this)

      "scripts": {
        "start": "node start.js",
        "dev": "nodemon start.js"
      },

So we have created two scripts one for production level “start”, and other for development “dev”. We are using nodemon for watching the changes and reloading the app. Your final package.json file should look something like this:

    {
      "name": "myapp",
      "version": "0.0.1",
      "private": true,
      "scripts": {
        "start": "node start.js",
        "dev": "nodemon start.js"
      },
      "dependencies": {
        "cookie-parser": "~1.4.4",
        "debug": "~2.6.9",
        "esm": "^3.2.25",
        "express": "~4.16.1",
        "http-errors": "~1.6.3",
        "jade": "~1.11.0",
        "morgan": "~1.9.1"
      },
      "devDependencies": {
        "nodemon": "^1.19.1"
      }
    }

Let’s try running our app again :P

It works ! Congrats :D, So now our App supports ES6.

In the next part, we will connect mongodb database to our Express App using Mongoose.

You can read the next part here :)

Don’t Forget to subscribe and drop comments below :D

Stay Tuned !