Build Blog using Nodejs with Express and Mongodb

Introduction

Welcome to Dynamic Blog Nodejs tutorial, in which we develop a dynamic website with CRUD operations that might be used to manage the blog articles and pages.

SampleBlog is the name of the dynamic ExpressJs application that we’ll create a series of tutorials. As you’d expect, the purpose of the dynamic website is to provide an online admin panel for posting blog articles on our SampleBlog, where blog user can browse available posts and maintain their user accounts.

In this tutorial articles, we will create a simple blog that blog visitor can read blog posts are available. This allows us to explore the operations that are common to almost every blog application, retrieving article content from a database.

Now that you know a bit more about the dynamic web application and what you’re going to learn, it’s time to start creating a blogging application project to contain our example.

in this article shows how you can create a “Dynamic Blog” using the NPM Application Generator tool, which you can then populate with website-specific routes, views/render templates, and database calls using mongo cloud on Mlab. In this case, we’ll use the tool to create the framework for our sample blog application, to which we’ll add all the other code step by step needed by the blog. The creating site is extremely simple, requiring only that you invoke the generator on the command line interface with a new project name, optionally also specifying the site’s different template engine and CSS styles generator.

Firstly, you should install the generator tool site-wide using the Node package manager.

=> npm install express-generator -g

Which view engine should I use?

The Express Application Generator enables you to design various famous view/templating engines, including EJS, Hbs, Pug (Jade), Twig, and Vash, although it chooses Jade by default if you don’t specify a view option. Express itself can likewise an extensive number of other templating languages

a] Time to Probability:- If you already have experience with a templating language then it is likely they will be beneficial quicker utilizing that language. If not, then you should consider the relative expectation curve for candidate templating engines.

b] Popularity and activity:- Review the popularity of the performance and whether it has a functional network. It is important to be able to get support for the system when you have issues over the lifetime of the site.

c] Style:– Some template engines format utilize particular markup to show embedded substance inside “customary” HTML, while others develop the HTML utilizing an alternate language structure (for instance, utilizing space and square names). Execution/rendering time.

Creating the project

For our sample blog Application, we’re going to build, we’ll create a project named simple blog tutorial using the Pug, formerly known as “Jade” template library and no CSS stylesheet engine.

Firstly go to command prompt and create a project and then run the Express Application Generator in the command line prompt as shown:

=>  express sampleblog –view=pug

Install NPM dependencies:

=> cd sampleblog && npm install

Run the app:

=>  SET DEBUG=sampleblog:* & npm start

Running the architectural express website

At this point, we have a complete structure of Application. The site doesn’t actually do very much yet, but it’s worth running it to show how it works.

First, we install the NPM dependencies. the following command will fetch all the dependency packages listed in the application package.json file.

=> cd sampleblog

=> npm install

Then run the application :-

=> SET DEBUG=sampleblog:* & npm start

then load application on localhost. The generated application structure:

/sampleblog
    app.js
    /bin
        www
    package.json
    /node_modules
    /public
        /images
        /javascripts
        /stylesheets
            style.css
    /routes
        dashboard.js
        users.js
    /views
        error.pug
        dashboard.pug
        layout.pug

Let’s now take a look at the Directory structure we just created.

The generated app structure, now that you have installed all dependencies, has the following file structure. The package.json file defines the application dependencies and other starter information. It also defines a startup script that will call the application entry point, the JavaScript files /bin/www. This sets up a portion of the application error dealing with and afterward stacks app.js. The application routes are stored in separate modules under the routes directory folder. The templates are stored under the /views directory folder.

what is package.json?

The package.json file defines all application dependencies and other declaration: The dependencies inside the express package and the package. In addition, we have the following some required packages that are useful in many web applications:

{
  "name": "sampleblog",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.18.2",
    "cookie-parser": "~1.4.3",
    "express": "~4.16.2",
    "debug": "~2.6.9",
    "morgan": "~1.9.0",
    "pug": "~2.0.0-rc.4",
    "serve-favicon": "~2.4.5"
  },
  "devDependencies": {
    "nodemon": "^1.14.11"
  }
}

1] Body-parser: This parses the body part of an incoming HTTP request and makes it easier to read POST parameters.

2] Cookie-parser: it is used to parse the cookie header data and populate req.cookies provides cookie information.

3] Debug: A small node debugging utility used after node core’s debugging technique.

4] Morgan: it’s HTTP request logger middleware for node app.

The scripts section defines a “start” script for bootstrap the application, which is what we are invoking when we call NPM Start to start the application server. From the script definition, you can see that this actually starts the JavaScript file ./bin/www with node starter. It also defines a “Devstart” script for running application.

what is www file?

In node application /bin/www file is the entry point of application. The first thing this does is require() the “real” application entry point because of it import the express() application object.

/**
 * Module dependencies.
 */

var app = require('../app');
line the require() is a global node function that is used to import modules with objects into the current file.

what is app.js ?

This file creates an express application object and set up the application with various configuration and middleware, and then exports the app from the main module. The following code shows just the parts of the file that create and export the app object to other controllers and routes, using the module.exports syntax.

var express = require('express');
var app = express();
...
module.exports = app;

Setup for view engine

First, we create the app object using our imported express module and then use it to set up the view engine template. There are two sections to Setting up the engine. First, we set the ‘views’ value to specify the directory where the templates will be stored in the Subfolders. At that point, we set the ‘view engine’ esteem to determine the layout library. in Express module provide different view engine templates. and our application we define pug view engine.

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

setup for static files

In our application import 3rd party libraries, then we use the express.static middleware to get Express to serve all the static files inside the /public directory in the project root.

// other dependencies 
app.use(express.static(path.join(__dirname, 'public')));

Setup route handling chain

we add our route-handling code to the request handling pipeline. The imported code will define specific routes path for the specific controller.

app.use('/', indexRouter);
app.use('/users', usersRouter);

How Routes works?

The route file /routes/dashboard.js is shown below. First, it loads the express module for Initialize the express.router object. At the Point, it indicates that object, and in Conclusion, sends out the switch from the module.

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond data');
});
module.exports = router;

The route defines a callback that will be Call whenever an HTTP GET request with the correct pattern is detected. The matching pattern is the route specified when the module is imported (‘/dashboard’) and whatever is defined in this file (‘/’)

How to Routes works with views ?

The views templates are stored in the /views folder and are given the file extension .pug. The strategy Response.render() is utilized to render a specified layout along with the values of named factors passed in an object, and then send the result as a response. In the code below from /routes/dashboard.js you can perceive how that course renders a reaction utilizing the format “dashboard” passing the layout variable “UserName”.

/* GET page. */
router.get('/', function(req, res) {
  res.render('dashboard', { title: 'Express' });
});

The corresponding template for the above route is given below dashboard.pug

extends layout

block content
  h1= UserName
  p Welcome to #{UserName}

Thanks for Reading Article! I hope this get’s you started app using Node and ExpressJs. Take care.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *