Below is an example of converting a text to qr code.
var QRCode = require('qrcode');
var express = require('express');
var connect = express();
connect.get('/', function(req, res){
res.writeHead(200, { 'Content-Type': 'text/html' });
var sometext='hi my name is saurav ghadai';
// QRCode.QRCodeDraw.color.dark = '#d4d4d4';
QRCode.toDataURL(sometext, function (err, url) {
if (err) console.log('error: ' + err)
res.end("<!DOCTYPE html/><html><head><title>node-qrcode</title></head><body><img src='" + url + "'/></body></html>");
});
});
connect.listen(3030);
console.log('test server started on port 3030');
like this how can we create qr code for a json object ?
You can use JSON Strigify method to convert your JSON object into text. Then use the text output into your QR generator method
Related
I have an express service which has an endpoint that consumes a POST call with form-data in XML.
Postman Call
I'm using multer and express-xml-bodyparser and my index.js looks like:
'use strict';
const express = require('express');
const app = express();
const xmlparser = require('express-xml-bodyparser');
const multer = require('multer')
const upload = multer()
const redact = { redact: ['body.*', 'value.body'] };
const modsRoute = require('./routes/mods');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(xmlparser());
app.use(upload.none());
app.post('/request', modsRoute.postMethod)
module.exports = app;
The problem is that when I try to print the content of the request body in my router method:
const postMethod = async (req, res, next) => {
try {
console.log('body: ', req.body);
res.status(200).send();
} catch (err) {
next(err);
}
};
I get a weird object:
body: [Object: null prototype] {
'api-key': '1a393779-c191-11e3-ae50-80c16e6a4098',
data: '<subscriber>\n' +
'\t<action>add</action>\n' +
'\t<customer_id>529</customer_id>\n' +
'\t<subscriber_details>\n' +
' <unique_id>123UniqueID</unique_id>\n' +
'\t\t<firstname>First</firstname>\n' +
'\t\t<lastname>Test</lastname>\n' +
'\t\t<address1>999 Street</address1>\n' +
'\t\t<address2></address2>\n' +
'\t\t<city>Scottsdale</city>\n' +
'\t\t<state>AZ</state>\n' +
'\t\t<zip>85253</zip>\n' +
' <email>email#infoarmor.com</email>\n' +
' <dob_month>00</dob_month>\n' +
'\t\t<dob_day>00</dob_day>\n' +
'\t\t<dob_year>0000</dob_year>\n' +
'\t\t<phone>9999999999</phone>\n' +
'\t\t<options>\n' +
'\t\t\t<plan_type>1</plan_type>\n' +
' <ew_status>0</ew_status>\n' +
'\t\t</options>\n' +
'\t\t<billing_information>\n' +
'\t\t\t<bill_type>prd</bill_type>\n' +
'\t\t</billing_information>\n' +
'\t</subscriber_details>\n' +
'</subscriber>'
}
As it can be seen, the object contains all the newline and whitespace characters and it hasn't really converted it into JSON.
I also tried to convert the whole body into JSON with JSON.parse() but I got an exception thrown. I also tried to first stringify() the body and then parse it.
In that case, I could only get the data field but I was again an expection when trying to get the api-key field.
Do I need to add any other middleware in order to get at least a correct JSON object of req.body even though the field data is still in XML and not JSON?
You can send json data to user using like this
const postMethod = async (req, res, next) => {
try {
res.json({"Hello":"World"});
// you can send anything json back including req.body like
// this res.json(req.body);
} catch (err) {
next(err);
}
};
I dont understand why I cant display my json data. I am new to javascript and I want to display the data in the json file to my index file.
I have used the express generator for all the files. I did read that I should add this FS code in my app.js, but I cant use the data variable in my index file in my view. Any help ?
var express = require('express');
var router = express.Router();
var fs = require('fs');
/* GET home page. */
router.get('/', function(req, res, next) {
var file = __dirname + '/public/list/list.json';
var data;
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.log(data);
});
res.render('index', { title: data });
console.log(data);
});
module.exports = router;
here is my json file
{
"username":"xyz",
"password":"xyz#123",
"email":"xyz#xyz.com",
"uid": 1100
}
fs.readFile is asynchronous , so you should put res.render(..) inside his callback , because it will fired when the readFile function ends. So change your code to :
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.log(data);
res.render('index', { title: data });
});
The above answer is correct, but there's also an alternative.
If you're using this file for your index page, it'd be used a lot. If the data isn't changing, you can simply require the JSON file at the top of your code and return it in the request.
var express = require('express');
var router = express.Router();
var list = require(__dirname + '/public/list/list.json');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: list });
});
module.exports = router;
However, if that data does change frequently, reading the file is the way to go.
I am working on a MEAN stack app, and I'm trying to create a couple of API endpoints that the Angular client can $http.get, with simple JSON files populated with dummy data.
Here's the orders.json file I'm trying to test it with:
[
{
"order_status":"Shipped",
"order_qty":30
},
{
"order_status":"Shipped",
"order_qty":6
}
]
For example, the api route to $http.get:
apiRouter.get('/:fileName', queries.getStaticJSONFileForDevelopment);
But when I try to use express's sendFile method with a local .json file, like orders.json:
queries.js:
exports.getStaticJSONFile = function(req, res) {
var fileName = req.params.fileName;
console.log('path: ' + path.normalize(__dirname + '/' + fileName));
res.sendFile(path.normalize(__dirname + '/' + fileName), function(err) {
if (err) return res.send({ reason:error.toString() });
});
};
The console.log tells me I'm pointed at the correct path to the file, but Postman delivers this error:
TypeError: undefined is not a function
at Object.exports.getStaticJSONFile [as handle] (path/to/queries.js:260:7)
// queries.js:260:7 points to the 's' in 'sendFile' above
However, when I just send the json data by itself:
res.send([{"order_status":"Shipped","order_qty":30},{"order_status":"Shipped","order_qty":6}]);
...the endpoint renders the data as you would expect. Am I trying to get the sendFile method to do something it's not meant to do, or is there something I'm missing? Thanks very much for any advice you may have!
If You want to read json file and response with json so You can try this:
var jsonfile = require('jsonfile');
exports.getStaticJSONFile = function(req, res) {
var fileName = req.params.fileName;
var file = path.normalize(__dirname + '/' + fileName);
console.log('path: ' + file);
jsonfile.readFile(file, function(err, obj) {
if(err) {
res.json({status: 'error', reason: err.toString()});
return;
}
res.json(obj);
});
};
I am a node.js beginner and I am trying to read a json file, but when I'm running 'npm start' in the terminal I get this error:
undefined:3462
SyntaxError: Unexpected end of input
at Object.parse (native)
at /Users/alonbond/node_apps/analoc_2/analoc/routes/index.js:15:20
at fs.js:334:14
at FSReqWrap.oncomplete (fs.js:95:15)
this is index.js:
var express = require('express');
var fs = require('fs');
var app = express.Router();
/* GET home page. */
app.get('/', function(req, res, next) {
console.log('Welcome to Express.js');
res.render('index', { title: 'Express' });
});
/* GET json */
app.get('/analoc/', function(req, res) {
fs.readFile('./sample_data.json', function(error, data){
jsonObj = JSON.parse(data);
res.send('THE DATA: ', jsonObj);
});
});
module.exports = app;
Any help?
thanks!
readFile is the asynchronous version. You should either just use readFileSync, or rewrite it to be properly asynchronous.
console.log('analoc request');
var fs = require('fs');
fs.readFile('./files/sample_data.json', function(err,config){
console.log('Config: ' + JSON.parse(config));
});
Or:
var config = fs.readFileSync('./files/sample_data.json');
console.log('Config: ' + JSON.parse(config));
readFile doesn't have a return value. You are trying to parse "undefined" as if it were JSON. The file is passed to the callback function after it has been read.
fs.readFile('./files/sample_data.json', function (err, data) {
if (err) throw err;
var config = JSON.parse(data);
console.log('Config: ', config);
});
i return the array from node.js
reading xml content from txt file and store in array send to html page using ajax method how do this task.
xml2js = require('xml2js');
fs = require('fs');
var arr={};
var parser = new xml2js.Parser();
fs.readFile('D:/test.txt', function(err, data) {
parser.parseString(data, function (err, result) {
arr=result.Cluster.Array[0].String;
});
});
app.get('/test', function(req, res, next) {
res.json({ message: arr }); //passing array data
});
how to display in html page current i used. But i get whole data in console log not able to display in html page get message undefined :
$.ajax({
url: '/test',
complete: function(data) {
JSON.stringify(data);
console.log(data.message);
// document.write(data.message);
for(i=0;i<data.length;i++)
{
document.write(data.message[i].Val);
$('#did').append('<h1>'+data.message[i].Name+'</h1>');
}
}
use a ReadStream, and stream it into your httpResponse
stream = fs.createReadStream "path/to/file.json"
stream.pipe(res)