Skip to main content

How to Create and Read QR Code in Node.js

Introduction

In this post, you will learn how to Create a QR code in Node. 

Project Structure

This is image title

Setup the Folder

First, we have to create a folder for our project.

  • Open the command prompt /terminal and type mkdir command followed by the folder name.

    # mkdir qrcodee

  • Now change to that folder using cd followed by the folder name.

    # cd qrcodee

Setup Node in Folder

To setup node in the folder, we have to type the following command from the command prompt/terminal.

# npm init -y

This will create a package.json file in the folder which means that Node has been set up in our folder. The file will look like this.

{    
  "name": "qrcodee",  
  "version": "1.0.0",    
  "description": "",    
  "main": "index.js",    
  "scripts": {    
    "test": "echo \"Error: no test specified\" && exit 1"    
  },    
  "keywords": [],    
  "author": "",    
  "license": "ISC"    
}   

Install Packages

To build our application, we need to install packages. For installing the packages, we have to use the below command followed by the package name.

# npm install body-parser ejs express mongoose QRcode

After the packages are installed, the package.json will look like this.

{    
  "name": "qrcodee",    
  "version": "1.0.0",    
  "description": "",    
  "main": "index.js",    
  "scripts": {    
    "test": "echo \"Error: no test specified\" && exit 1"  
  },    
  "keywords": [],    
  "author": "",    
  "license": "ISC",    
  "dependencies": {    
    "body-parser": "^1.19.0",    
    "ejs": "^3.0.1",    
    "express": "^4.17.1",    
    "mongoose": "^5.8.11",    
    "qrcode": "^1.4.4"    
  }    
}  

Add New Folders

Now add 2 new folders in our project folder:

  • models
  • views

Models Folder

Add a file to it and name it user.js.

user.js

var mongoose    =   require('mongoose');    

var userSchema  =   new mongoose.Schema({    
    name:{    
        type:String    
    },    
    phno:{    
        type:Number    
    }    
});    

module.exports = mongoose.model('user',userSchema);   
  • mongoose.schema() - this is used to create the collection(table) schema.
  • mongoose.model() - here we will provide the name to our schema by which we can access it and can do data manipulation in it.

Views Folder

Add a new file to it and name it home.ejs

home.ejs

<html lang="en">    
<head>    
    <meta charset="UTF-8">    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">    
    <meta http-equiv="X-UA-Compatible" content="ie=edge">    
    <title>Qrcode</title>    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">    
</head>    
<body>    
    <div class="nav justify-content-center">    
    <div class="card border-primary mb-3" style="max-width: 18rem;margin-top: 20px;">    
        <div class="card-header">User Details</div>    
        <div class="card-body text-primary">    
            <form action="/" method="post">    
                <input type="text" name="name" placeholder="enter the name" class="form-control"><br>    
                <input type="text" name="phno" placeholder="enter the phone number" class="form-control"><br>    
               <div class="text-center"> <input type="submit" value="get qrcode" class="btn"> </div>     
             </form>    
        </div>    
      </div>    
    </div>    
    <%if(data){%>     
        <div class="text-center">    
         <h5>Scan QRCode</h5>    
        <img src="<%=data%>" alt="" style="width:100px; height:100px;">    
         </div>    
    <%}%>      
</body>    
</html>   

Set The Start Point

In the project folder add a new file and name it app.js.This is the starting point of our application

app.js

var express     =   require('express');    
var mongoose    =   require('mongoose');    
var userModel   =   require('./models/user');    
var bodyParser  =   require('body-parser');    
var QRCode      =   require('qrcode');    

//connect to db    
mongoose.connect('mongodb://localhost:27017/qrdemo',{useNewUrlParser:true})    
.then(()=>console.log('connected to db'))    
.catch((err)=>console.log(err))    

//init app    
var app = express();    

//set the template engine    
app.set('view engine','ejs');    

//fetch data from the reuqest    
app.use(bodyParser.urlencoded({extended:false}));    

//default page load    
app.get('/',(req,res)=>{    
       userModel.find((err,data)=>{    
          if(err){    
              console.log(err);    
          }else{    
              if(data!=''){    
                  var temp =[];    
                  for(var i=0;i< data.length;i++){    
                      var name = {    
                          data:data[i].name    
                      }    
                      temp.push(name);    
                      var phno = {    
                          data:data[i].phno    
                      }    
                      temp.push(phno);    
                  }   
                  // Returns a Data URI containing a representation of the QR Code image.  
                  QRCode.toDataURL(temp,{errorCorrectionLevel:'H'},function (err, url) {    
                    console.log(url)    
                    res.render('home',{data:url})    
                  });    
              }else{    
                  res.render('home',{data:''});    
              }    
          }    
       });    
});    

app.post('/',(req,res)=>{    
        var userr = new userModel({    
            name:req.body.name,    
            phno:req.body.phno    
        });    
        userr.save((err,data)=>{    
             if(err){    
                 console.log(err);    
             }else{    
                 res.redirect('/');    
             }    
        });    
});    

//assign port    
var port  = process.env.PORT || 3000;    
app.listen(port,()=>console.log('server run at '+port));   

Now open the package.json file and in the script, add "start":"node app.js"

The package.json file will look like this:

{    
  "name": "qrcodee",    
  "version": "1.0.0",    
  "description": "",    
  "main": "index.js",    
  "scripts": {    
    "test": "echo \"Error: no test specified\" && exit 1",    
    "start": "node app.js"    
  },    
  "keywords": [],    
  "author": "",    
  "license": "ISC",    
  "dependencies": {    
    "body-parser": "^1.19.0",    
    "ejs": "^3.0.1",    
    "express": "^4.17.1",    
    "mongoose": "^5.8.11",    
    "qrcode": "^1.4.4"    
  }    
}    

Comments

Popular posts from this blog

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...