sending parsed JSON file to client but format is not HTML - html

called the API, and parsed the JSON. Now want to display that parsed JSOn in table format in receiving page. it is coming as plain text.
API url is just for test purpose taken from WIKI, cannot post actual API for security purpose.
requiremtn is to send the HTMl file in table format as a output.
app.js file:
const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
var fs = require('fs');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res) {
const url = "https://en.wikipedia.org/w/api.php?
format=json&action=parse&page=Anthony%20Martial";
https.get(url, function(response) {
https.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
const jsonDATA = JSON.parse(data).parse;
var jsonText = jsonDATA.text;
var jsonTitle = jsonDATA.title;
var jsonPageid = jsonDATA.pageid
var str = JSON.stringify(jsonText);
var str1 = str.replace(/\\n/g, '');
const jsdom = require("jsdom");
const {
JSDOM
} = jsdom;
const virtualConsole = new jsdom.VirtualConsole();
const dom = new JSDOM(str1, {
virtualConsole,
runScripts: "dangerously",
resources: "usable"
});
var strWrite = dom.window.document.querySelector("table").textContent;
res.setHeader("Content-Type", "text/html");
res.write(strWrite);
res.send();
});
});
});
});
app.listen(3000, function(req, res) {
console.log("server is running in port 3000");
});
index.html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>weatehr App API</title>
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<form action="/" method="post">
<label for="cityInput">City Name:</label>
<input id="cityInput" type="text" name="cityName">
<button type="submit"> Go </button>
<h3>hello</h3>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
output i am receiving:
in plaintext format:
Anthony MartialMartial playing for Manchester United in 2017Personal informationFull nameAnthony
Jordan Martial[1]Date of birth (1995-12-05) 5 December 1995 (age 24)[2]Place of birthMassy,
FranceHeight1.81Â m (5Â ft 11Â in)[3]Playing position(s)ForwardClub informationCurrent
teamManchester UnitedNumber9Youth career2001–2009CO Les Ulis2009–2012LyonSenior
careerYearsTeamApps(Gls)2012–2013Lyon B11(5)2013Lyon3(0)2013Monaco
B4(3)2013–2015Monaco49(11)2015–Manchester United143(51)National team‡2010–2011France
U1617(9)2011–2012France U1713(9)2012–2013France U184(3)2013France U195(0)2013–2015France
U2112(4)2015–France18(1) Honours Representing  FranceMen's footballUEFA European
ChampionshipRunner-up2016 France Senior club appearances and goals counted for the domestic
league only and correct as of 21:16, 16 July 2020 (UTC)‡ National team caps and goals correct
as of 27 March 2018

Issue resolved.
option1:
using repalce statement that parsed JSON escape charatacter has been removed from the string.
An now the display it exactly in table format.
option2:
concatenate and tag then at the end close tag .
Then it is coming as a table.

Related

node.js formidable with express.js

I am new to node.js and learning it from various sources such as bootcamps, websites, etc.
I want to upload a file using formidable module in node.js and express.js framework. Everytime I run this code it show an error....
var oldpath = file.fileupload.path;
^
TypeError: Cannot read property 'path' of undefined
I have used body parser to receive the name of the file.
Node.js code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var formidable = require("formidable");
var fs = require("fs");
var PORT = process.env.PORT || 5000
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.get("/" , function(req, res){
res.render("form");
});
app.post("/fileupload" , function(req, res){
var fileupload = req.body.filetoupload;
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
var oldpath = files.fileupload.path;
var newpath = "C:/Users/ayush/"+files.fileupload.name;
fs.rename(oldpath, newpath, function(err){
if(err)
console.log(err);
else{
res.write("File Uploaded");
res.end();
}
});
});
});
app.listen(PORT, function(){
console.log("Server started");
});
<!DOCTYPE html>
<html>
<head>
<title>FileUpload</title>
</head>
<body>
<form action="/fileupload" method="POST">
<label>
File:
<input type="file" name="filetoupload" enctype="multipart/form-data">
</label>
<button>Submit</button>
</form>
</body>
</html>
I'm new at this too but the form enctype in form.ejs should be in the <form> tag.
Instead of:
<form action="/fileupload" method="POST">
try:
<form action="/fileupload" method="POST" enctype="multipart/form-data">
You should now have your files object.
Cheers,
Mark
This is a complete working example:
upload.js
'use strict';
const fss = require('fs')
const pth = require('path');
const exp = require('express');
const swg = require('swig');
const efm = require("formidable");
const app = exp();
const thm = swg.compileFile(pth.join(__dirname, '', 'upload.html'));
app.listen(9009);
app.get(`/`, async (q, r) => r.send(thm({ msg: "Select a File to Upload" })));
app.get(`/:msg`, async (q, r) => r.send(thm({ msg: q.params.msg })));
app.post('/upload', (r, q) => {
var form = new efm.IncomingForm();
form.parse(r, (e, p, f) => {
let dir = pth.join(__dirname, '', '/media/');
if (!fss.existsSync(dir)) {
fss.mkdirSync(dir);
}
let nPth = dir + f.file.name;
try {
fss.accessSync(nPth, fss.F_OK);
q.redirect("/File Exists");
} catch (file_e) {
let err = fss.renameSync(f.file.path, nPth);
q.redirect(err ? "/Error" : "/File Uploaded");
}
});
});
You can use fss.access for "A-SYNC" operation.
Its better to use "A-SYNC" functions.
upload.html
<h3>{{msg}}</h3>
<br/>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
fileupload object doesn't exist within file, hence you are getting the undefined error.
To access the old path use :
var oldpath = files.upload.filepath;

Send data from SerialPort to socket.io

I'm struggling with socket.io, express, and node.js.
I send data from an Arduino to my cmd. This is done with the serialport libary. But now I want this data displayed on my web browser. I'm using the express library for this. I have index.js here is the connection with the arduino and browser. And an index.html
This code do I have:
code from index.js (node.js server):
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket){
connectedSocket = socket;
}
//Arduino to CMD
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM4');
const parser = usbport.pipe(new Readline());
parser.on('data', console.log);
The data what is recieved from the serialport (Arduino), had to be displayed in the index.html (webbrowser). I tried already something but it doesn't work. It has to be printed in the <p></p> in the html code.
The index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="text">
<p></p>
</div>
<script>
var text = document.getElementById('text');
var socket = io.connect('http://localhost:8888');
socket.on('data', function(message) {
text.innerHTML = message.data;
});
</script>
</body>
</html>
Instead of
parser.on('data', console.log);
Try this:
parser.on('data', function (data) {
io.emit('data', { data: data });
});
That should send the parsed data from the SerialPort to the socket, which should end up on the client side on the website.

Not able to print table

I'm sending the table created in node js to the html web page but the table boundary is not getting printed instead some random characters and symbols are getting printed.
the node js code is :
var express = require('express');
var app = express();
var fs = require('fs')
var googlePlaySearch = require('google-play-search');
var prettyjson = require('prettyjson');
app.use(express.static('public'));
var csv = require('csv');
var Table = require('cli-table');
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
});
app.get('/process_get', function (req, res) {
first_name:req.query.first_name
googlePlaySearch.fetch(req.query.first_name, function(err, response) {
var data =
'Category,name\n' +
response.categories + ' ' +
response.name ;
var chars = {
'top': '═', 'top-mid': '╤', 'top-left': '╔', 'top-right': '╗',
'bottom': '═', 'bottom-mid': '╧', 'bottom-left': '╚',
'bottom-right': '╝', 'left': '║', 'left-mid': '╟', 'mid': '─',
'mid-mid': '┼', 'right': '║', 'right-mid': '╢', 'middle': '│'
};
csv().from.string(data).to.array(function(data) {
var
headers = data[0],
values = data.slice(1),
aligns = [null,'right'],
table = new Table({ head: headers, chars: chars, colAligns: aligns })
;
table.push.apply(table, values);
console.log(table.toString());
});
});
});
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
})
and the html code is (index.htm)
<!DOCTYPE html>
<html>
<head>
<title>Package Details</title>
</head>
<body>
<h1><marquee style="color:yellow" >this is a page to find app details.. </marquee></h1>
<center>
<form id="f1" action="/process_get" method="GET">
<h3 style="color:red">Package Name</h3>:<br>
<input type="text" name="first_name"> <br><br>
<input type="submit" value="Submit" style="font-size: 20px">
</form>
</center>
</body>
</html>
Please help me with the code

Why hasOwnProperty returns false?

I cant understand why hasOwnProperty return false on the following scenario:
Client side:
<html>
<head>
<script type="text/javascript">
var client = [
{"clientName":"", "clientNickName": ""},
{"clientName":"", "clientNickName": ""},
{"clientName":"", "clientNickName": ""}
];
function onSubmit() {
// update data
client[0].clientName = "AAA";
client[0].clientNickName = "BBB";
client[1].clientName = "CCC";
client[1].clientNickName = "DDD";
client[2].clientName = "EEE";
client[2].clientNickName = "FFF";
// create request
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","~/process_post",true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
// send
xmlhttp.send(JSON.stringify(client));
return true;
}
</script>
</head>
<body >
<form action="http://127.0.0.1:8081/process_post" method="POST">
User Name:
<input type="text" name="userName">
<br>
Nick Name:
<input type="text" name="nickName">
<br>
<input type="submit" value="Submit" onclick="return onSubmit()">
<br>
</form>
</body>
</html>
server side:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(express.static('public'));
app.post('/process_post', function (req, res) {
var x = req.body;
if (x[0].hasOwnProperty('clientName')) {
console.log("yes: clientName exsists");
}
console.log("result: " + req.body);
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I have updated the Q, after get some comments which didnt help.
Why the server does not parse the json data properly ?
The server crash when calling hasOwnProperty on x[0]:
"TypeError: Cannot read property 'hasOwnProperty' of undefined"
Thanks
First thing is that you cannot send an array as a raw object.
You need to send a string representation of it.
Use xmlhttp.send( JSON.stringify(client) );
Then, when you do var x = req.body; you assign the array to the x variable.
So you need to test its items for the property you want and not the array itself.
Try x[0].hasOwnProperty('clientName')

AJAX request on Node.js server

I am unable to make an AJAX request from my .html page to my node.js server for a JSON file. I've been reading on AJAX requests, but all I am able to make out is how to display the servers responseText.
It would be great if you could help me out, it would be even better if you could link me some tutorials on this, anyway this is what I've got at this moment:
server.js
var express = require('express');
var fs = require('fs');
var app = express();
app.get('/test', function(req, res){
var arr = new Array();
var rd = readline.createInterface({
input: fs.createReadStream('info.json'),
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
arr.push(line);
}).on('close', function(){
res.send(arr);
});
});
app.get('/', function(req, res) {
fs.readFile('test2.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.listen(process.env.PORT || 3000);
test.html
<html>
<head>
<script>
function sendAjax(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4 && xmlHttp.status == 200){
console.log(xmlHttp.responseText);
}
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
}
xmlHttp.open("GET", "/test", true);
xmlHttp.send();
}
</script>
</head>
<body>
<input type="submit" onClick="sendAjax()" value="SendAjax" />
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
</body>
</html>
I know this may not look like much, I've been struggling with this, and the book I have (Node.js in Action) doesn't help me alot. But as I said, what I want is to display the .json info in the browser. Thx for reading
If I understand right, you may replace
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
with
var parsed = JSON.parse(xmlHttp.responseText);
var html = '';
for (var i = 0; i < parsed.length; i++) {
html += '<div>' + parsed[i] + '</div>';
}
document.getElementById("myDiv").innerHTML = html;
You may also try to replace
res.send(arr);
with
res.json(arr);
Update
Or maybe you just forgot to write this line in the beginning of server.js:
var readline = require('readline');