Email: info@zenconix.com

Use template to Express – Pug



Visit Site:

Overview

In this post, we are going to take a look on how to use template to our express js application, in this post we are going to focus on using Pug template to our application.


If you have not yet read previous blog posts on Node, please take a look on it as this post is in continuation with previous blog posts.

http://zenconix.com/create-node-app-with-express-js/

http://zenconix.com/create-routes-in-express-js/


First step, we need to install pug plugin to our application, to install it, open terminal and enter command as

npm install pug --save

Detailed information about pug js can be found on their official website – https://pugjs.org/api/getting-started.html

Next, we need to tell our express application that, we are going to use pug as view engine, open app.js file and write below code there

app.set('view engine', 'pug');

We are going to create all views of our application into Views folder, so create folder named – views in root folder of our application.

Inside views folder , we have created view for home page by name “home.pug”

We will back to our home view in minute, but before that, we need to tell our express application that, it has to use this “views” folder to find out the view for rendering. So go back to app.js file and tell our application, that it has to use “views” folder to find out the views.

app.set('views', 'views'); 

Here we are using set function of middleware, all information about it can be found on Express Js website – https://expressjs.com/en/4x/api.html#app.set

Now, we will create new router for home page, where we have to render home.pug file as response of the request.

Create new router for home in user.js file.

router.get('/home', (req, res, next) => {
    res.render('home');
 });

Notice here, we are using render() function to call home view without extension of file i.e. pug.

Now, go back to our home.pug file and write down the code as below.

html
  head
    title HomePage
  body
    h1 welcome to home page

In pug, we dont need to open and close the tags, we just need to write them once and enter text whatever you want to add beside the tags.

Syntax of pug file can be found at their website – https://pugjs.org

Time to check our application, open terminal and start our application.

npm start

Remember, we have already installed and configured nodemon in our application, if you have not yet done, please go through blog post https://zenconix.com/use-nodemon-in-node-app/

After you run application, go to url http://localhost:3000/home

and if you see its source code, it is same as our normal HTML, pug engine does everything for us.

We also can make our HTML page dynamic by passing the values from js file. Let’s pass title of the page and message to print on the page from our router file.

Modify our response as below.

router.get('/home', (req, res, next) => {
    res.render('home',
        {
            pageTitle: 'Home',
            pageMessage: 'welcome to home page!'
        });
 });

Here, we are passing title and message to home view, modify our Home.pug file as below

html
  head
    title=pageTitle
  body
    h1=pageMessage

now if we check our application, we will see the result as expected


Add CSS to our application

Now, we will add CSS to our application, but before doing that, we need to create a folder in our application which will be exposed to end user to access, in that folder we will store all files which are accessible to all user.

Let’s create a folder named “Public” in our application, inside public, create another folder called “css” where we will keep all our css files. Finally, create css file – style.css

We need to follow couple of steps here to add css file to our application.

First, we need to tell our application to allow our public folder to access to users, so css file and other files inside it (example images and videos etc) will be accessible to users.

We will use core module of node i.e. path, to use path module, add following line in our app.js

const path = require('path');

Now, we have one variable in node which gives us directory name, i.e. __dirname

Now, tell our node app to allow all user to access public, write below code in app.js file

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

express.static() function will allow user to access public folder which is inside our directory (directory name will be fetched by __dirname

Time to add css file reference in home.pug file, add following line in home.pug

link(rel="stylesheet", href="/css/style.css")

Remember one thing, indentation in pug file is very important, if you missed to indent it properly, there will be run time error or unexpected result. Now our home.pug file will look like below.

html
  head
    title=pageTitle
    link(rel="stylesheet", href="/css/style.css")
  body
    h1=pageMessage

For simplicity , I just added one line of css to style.css file

h1{
    color:red; 
}

Save the file, go to browser and go to home router http://localhost:3000/home


Add Common Layout to application

Now we are going to create common layout for our views.

Create new folder named “layout” inside the views folder and create a layout named main-layout.pug (you can give any name you want)

now move common code from home.pug to main-layout.pug file, so our main-layout.pug file would be as below.

html
  head
    title=pageTitle
    link(rel="stylesheet", href="/css/style.css")
  body
  block content

Note; I have just moved common code and code which is uncommon (code which will be vary from file to file) will be a part of block, for now, I have added block name content, you can give any name to block, example block uncommon-area

Now, open our home.pug file and add reference of main-layout.pug file there and rest of our content.

extends layouts/main-layout.pug
block content
    h1=pageMessage

Save and refresh the browser, you will see result as expected.

Features

Specifications

Preview

Use nodemon in Node app



Visit Site:

Overview

In last couple of post, we are looking for how to work with Express Js.
If you have not yet seen the post, please take a look at the posts below.

http://zenconix.com/create-node-app-with-express-js/

http://zenconix.com/create-routes-in-express-js/

When we change anything in our code, we need to restart node server by command in terminal as node app.js

This is quite hectic, we should have something which will restart the application for us when we do the changes.


There is one npm package, called nodemon – which automatically restart the server for us.

You can find the detailed information about nodemon on their official website

https://nodemon.io/

and It’s npm package URL – https://www.npmjs.com/package/nodemon

Let’s include this in our project, to add this go to terminal and enter command as below

npm install nodemon --save-dev

As we need this for our development environment only, we need to add it as developer dependency , to do that just add --save-dev at the end while installation.

After installation, go to package.json file and add below configuration in script section

"start": "nodemon app.js"

So our script section will look something like below.

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  }

Now go to terminal and enter command as npm start, it will start our node server using nodemon and if you change in any file, you don’t need to start the application again and again as before, nodemon will take care of this for us.

Happy Coding 🙂

Features

Specifications

Preview

Create routes in Express Js



Visit Site:

Overview

In last post, we have seen how to create express js application in node.

http://zenconix.com/create-node-app-with-express-js/

In this post, we are going to take a look on how to create routes in express application.

To add routes in our application, we need to add middlewares, detailed information about middlewares in express js is available at the link

https://expressjs.com/en/guide/writing-middleware.html

to add routes in our file, we can use “use” middleware or also can use http method which middleware applies. e.g. get/ post etc.

Following figure shows elements of middleware function calls;

Image by Express Js
https://expressjs.com/en/guide/writing-middleware.html

lets take an example of using “use” middleware

app.use('/', (req, res, next) => {
    res.send('<h1>node application is running</h1>'); 
})

run the node application using node app.js command

Open the browser, and enter url as http://localhost:3000/

Also if we check the headers for this request, you can see it has automatically taken method as GET method.

Instead of using “use” middleware, we can also use http method specific middleware to add routes in application.

Let’s take a look at GET method

app.get('/data', (req, res, next) => { 
    res.send('<h3> This is GET route </h3>'); 
})

Now stop the application and run it again using node app.js command

GET method

Now, check the header response , there we can see method is taken as GET and content-type is set to text/html automatically

Similarly POST request can be added as below.

To create a post request, we will first create form which will be used to add some data.

app.get('/add-data', (req, res, next) => {
    res.send(
        '<form action="/data" method="post"><input type="text" name="name"> <button type="submit">Submit</button></form>'
    );
});

Above is get router, to display the form and we have added action="/data" for form, so once it is submitted, it will redirect the page to /data route.

Now we will add Post route to get the data

app.post('/data', (req, res, next) => {
    console.log(req.body); 
})

Now lets try to run the application by node app.js and go to url
http://localhost:3000/add-data

Enter some data and submit and check for our console.

Post request – undefined

It has shown the data as undefined, this is because express app is not parsing the request body, to do that we need to parse the body.

We have plugin for body parsing, we will install that plugin.

npm install body-parser --save

now we need to add module to our app.js file.

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded()); 

now run the app by entering command node app.js in terminal and go to http://localhost:3000/add-data add some data textbox and hit enter and check console.

Post data

As we are getting this error in console, add extended property to body parser.

app.use(bodyParser.urlencoded({extended: true}));

and run again using node app.js command in terminal, go to http://localhost:3000/add-data add some data textbox and hit enter and check console.


As we have seen we can write our routes in app.js file but by doing this, our app.js file will be more bigger and not readable, so it is best practice to separate out this routes to elsewhere.

So lets create a folder name “Routers” in root folder of our application.

In “routers” folder, create two js files named admin.js and user.js

Folder structure

admin.js file will contain all routes required for admin role and user.js file will contain all routes required for user role.

Let’s create routes for user first

Go to user.js file, add express module and then initialize Router function from provided by express js as below.

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

move our get route to user.js file as below

router.get('/data', (req, res, next) => {
    res.send('<h3> This is GET route from user js </h3>');
});

Note: instead of using app.get, here we have use router.get function because we have initialize the router middleware here.

Finally, we need to export the router so that we can use that in another file using require function.

module.exports = router; 

Our complete user.js file will look as below.

const express = require('express');
const router = express.Router(); 
router.get('/data', (req, res, next) => {
    res.send('<h3> This is GET route from user js </h3>');
});
module.exports = router; 

To use user.js file’s route, we need to import this file to app.js

First import the module, as it is not core module, we need to give full path for module as below.

const userRoutes = require('./routers/user');

Then we need to pass this to middleware as below

app.use(userRoutes); 

Again run our node app by entering node app.js command in terminal and go to http://localhost:3000/data

Similarly, we can move our admin routes to admin.js file, our admin js file will be as below

const express = require('express');
const router = express.Router(); 
router.get('/add-data', (req, res, next) => {
    res.send(
        '<form action="/data" method="post"><input type="text" name="name"> <button type="submit">Submit</button></form>'
    );
}); 

router.post('/data', (req, res, next) => {
    console.log(req.body); 
})
module.exports = router; 

And accordingly, we need to import admin routes in our app.js file

const adminRoutes = require('./routers/admin'); 
app.use(adminRoutes);

Now, run our node js application again by entering command in terminal as node app.js and go to browser and enter urls you will get same result as before.


Finally we will see if there is unwanted router comes , then we need to throw a page for 404 not found.

Go to app.js file and add use middleware

app.use((req, res, next) => {
    res.status(404).send('<h3> 404 page not found, please try with different URL </h3>'); 
})

Now go to browser and add any URL which we have not yet handled in router.

also you can see status is shown as 404 in network tab

I hope this explained you , how to add routes in Express js.

Happy Coding 🙂

Features

Specifications

Preview

Create Node app with Express JS



Visit Site:

Overview

In this post, we are going to take a look on how to create Node application with Express JS.

You need to install node and npm in your machine.

Node can be installed from https://nodejs.org/en/download/

npm can be installed from https://www.npmjs.com/get-npm


To create application, open terminal and enter command npm init

It will ask you series of questions, you just have to answer them or can just press enter button to take its default value.

here, I just added entry point as app.js , you can keep it anything you want or even index.js also should be fine.

Once you enter Yes, it will create new file in selected folder named package.json, this file contains everything which we have mentioned above, packages information which we required to installed in app and some other configuration which we will required for future .

{
  "name": "node-express-app",
  "version": "1.0.0",
  "description": "Tutorial for node-express app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "express",
    "tutorial"
  ],
  "author": "PrasadG",
  "license": "ISC"
}

Next step, we need to install Express JS package by npm.

To install, express package open terminal and enter command

npm install express --save

this will install express package to our application and so it will update the package.json file as well.

New dependency is added in package.json file.

"dependencies": {
    "express": "^4.17.1"
  }

Also it has created new folder named “node_module” which contains express js plugin and its dependent plugins.

Now entry point for application, as we have mentioned our entry point will be app.js, we will create a file named app.js.

First step in app.js file is, we need to include module for express. To do it, simply write as below.

const express = require('express'); 

Second we need to initilize the express module, to do this, add below line of code

const app = express(); 

Then we need to listen the port

Here we need to specify the port number, it can be anything as you want. I have added as 3000.

app.listen(3000); 

Finally, our complete app.js file will look as below.

const express = require('express');

const app = express(); 
console.log("app is running"); 

app.listen(3000);

Here I just added console to check the output in console.

To run this app, open terminal and enter run the application by

node app.js

Our express app is running on port 3000.

By this way, we can create node application with express js.

In upcoming posts, we will take a look deeper into express js and how to work with it.

Happy Coding !

Features

Specifications

Preview