Introduction

In this blog, you will learn how to generate a QR code in Node.

Project Structure

| --------- models
| |-------- user.js
|
|---------- views
| |-------- home.ejs
|
|----------- app.js

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.
  1. {
  2. "name": "qrcodee",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "keywords": [],
  10. "author": "",
  11. "license": "ISC"
  12. }

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.
  1. {
  2. "name": "qrcodee",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "keywords": [],
  10. "author": "",
  11. "license": "ISC",
  12. "dependencies": {
  13. "body-parser": "^1.19.0",
  14. "ejs": "^3.0.1",
  15. "express": "^4.17.1",
  16. "mongoose": "^5.8.11",
  17. "qrcode": "^1.4.4"
  18. }
  19. }

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
  1. var mongoose = require('mongoose');
  2. var userSchema = new mongoose.Schema({
  3. name:{
  4. type:String
  5. },
  6. phno:{
  7. type:Number
  8. }
  9. });
  10. 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
  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  6. <title>Qrcode</title>
  7. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  8. </head>
  9. <body>
  10. <div class="nav justify-content-center">
  11. <div class="card border-primary mb-3" style="max-width: 18rem;margin-top: 20px;">
  12. <div class="card-header">User Details</div>
  13. <div class="card-body text-primary">
  14. <form action="/" method="post">
  15. <input type="text" name="name" placeholder="enter the name" class="form-control"><br>
  16. <input type="text" name="phno" placeholder="enter the phone number" class="form-control"><br>
  17. <div class="text-center"> <input type="submit" value="get qrcode" class="btn"> </div>
  18. </form>
  19. </div>
  20. </div>
  21. </div>
  22. <%if(data){%>
  23. <div class="text-center">
  24. <h5>Scan QRCode</h5>
  25. <img src="<%=data%>" alt="" style="width:100px; height:100px;">
  26. </div>
  27. <%}%>
  28. </body>
  29. </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
  1. var express = require('express');
  2. var mongoose = require('mongoose');
  3. var userModel = require('./models/user');
  4. var bodyParser = require('body-parser');
  5. var QRCode = require('qrcode');
  6. //connect to db
  7. mongoose.connect('mongodb://localhost:27017/qrdemo',{useNewUrlParser:true})
  8. .then(()=>console.log('connected to db'))
  9. .catch((err)=>console.log(err))
  10. //init app
  11. var app = express();
  12. //set the template engine
  13. app.set('view engine','ejs');
  14. //fetch data from the reuqest
  15. app.use(bodyParser.urlencoded({extended:false}));
  16. //default page load
  17. app.get('/',(req,res)=>{
  18. userModel.find((err,data)=>{
  19. if(err){
  20. console.log(err);
  21. }else{
  22. if(data!=''){
  23. var temp =[];
  24. for(var i=0;i< data.length;i++){
  25. var name = {
  26. data:data[i].name
  27. }
  28. temp.push(name);
  29. var phno = {
  30. data:data[i].phno
  31. }
  32. temp.push(phno);
  33. }
  34. // Returns a Data URI containing a representation of the QR Code image.
  35. QRCode.toDataURL(temp,{errorCorrectionLevel:'H'},function (err, url) {
  36. console.log(url)
  37. res.render('home',{data:url})
  38. });
  39. }else{
  40. res.render('home',{data:''});
  41. }
  42. }
  43. });
  44. });
  45. app.post('/',(req,res)=>{
  46. var userr = new userModel({
  47. name:req.body.name,
  48. phno:req.body.phno
  49. });
  50. userr.save((err,data)=>{
  51. if(err){
  52. console.log(err);
  53. }else{
  54. res.redirect('/');
  55. }
  56. });
  57. });
  58. //assign port
  59. var port = process.env.PORT || 3000;
  60. 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:
  1. {
  2. "name": "qrcodee",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1",
  8. "start": "node app.js"
  9. },
  10. "keywords": [],
  11. "author": "",
  12. "license": "ISC",
  13. "dependencies": {
  14. "body-parser": "^1.19.0",
  15. "ejs": "^3.0.1",
  16. "express": "^4.17.1",
  17. "mongoose": "^5.8.11",
  18. "qrcode": "^1.4.4"
  19. }
  20. }
References
  • https://www.npmjs.com/package/qrcode