In this post I would like to explain about how to create or generate the QR code using Node.js with dynamic data. It is simple code to generate the code, but it will help in many of our applications.
- For the accessing any content or links rather than display directly, display it in QR codes. It is a secure way to display those contents.
- What we are going to achieve with QR code, simple display it in your website for the apps links, websites, amount related.
-
How we are going to create or generate it
1. As earlier explained about install the Nodejs in your system.
2. How to install the packages
To install any packages we have to follow below command to install it globallynpm install -g [package name]
To install any packages we have to follow below command to install it application
npm install –save [package name]
3. In our application we need to install the below packages
1
2
3
4
5npm install --save body-parser
npm install --save express
npm install --save fs
npm install --save path
npm install --save qrcode4. Write the PORT number inside of your index.js or app.js file
1const PORT = 30005. Include the all packages in your app file
1
2
3
4
5const express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var fs = require("fs");
var QRCode = require('qrcode');6. Include the body parser and express in your code
1
2
3
4
5
6
7
8var app = express();
app.set('view engine', 'html');
app.use(bodyParser.json({limit: '50mb'}));
// parse requests of content-type - application/json
//app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.urlencoded({ extended: true ,keepExtensions: true}));
// parse requests of content-type - application/json
app.use(bodyParser.json())7. CORS for our application
1
2
3
4
5
6app.use(function(req, res, next) { //allow cross origin requests
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});8. Middileware for our application
1
2
3
4
5
6const logger = function (req, res, next) {
//console.log(req)
next()
}
app.use(logger)9. Generate the QR code with provide text
1
2
3
4
5
6
7
8
9app.get('/', (req, res) => {
QRCode.toDataURL('https://anillabs.com', function (err, url) {
templatePath = path.join(__dirname + '/code.html');
fs.readFile(templatePath, {encoding: 'utf-8'}, function(err,data){
data = data.replace(/##qUrl/g, url);
res.send(data)
})
})
})10. Application listen
1app.listen(PORT, () => console.log('Anil Labs QR Code generation on the port: ' + PORT))11. To display the code in your HTML file
1<img src="##qUrl" />12. Run the application
1node index.js
with the above the steps we can create or generate the QR code using Node.js
0 Comments