How to generate a pdf whenever save the data? - html

I need to generate a PDF whenever submitting the data from a html form. But PDF should not be a image of html page. I have used node.js for my server implementations. All the data that I have inserted from fields in the form should be included in the PDF. Also, I have used mongodb as my database.
var express=require('express');
var app=express();
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var outline=require('./schemas/outline');
var outcomes=require('./schemas/outcomes');
//making db connection
mongoose.connect('mongodb://127.0.0.1:27017/modulelist');
//checking db connection
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("connected to db");
});
//setting client location
app.use(express.static(__dirname+"/client"));
//setting body parser
app.use(bodyparser.json());
//Insert modulelist data to db
app.post('/SaveModuleList',function(req,res){
var mod=new outline(req.body);
mod.save(function(err,docs){
if(!err){
res.json(docs);
}else{
console.log(err);
}
})
});
app.post('/SaveOutcomesList',function(req,res){
var out=new outcomes(req.body);
out.save(function(err,docs){
if(!err){
res.json(docs);
}else{
console.log(err);
}
})
});
app.listen(3000,function(){
console.log("server runing in port 3000");
});

Related

nodejs server app.post issue XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:

I followed a tutorial on YouTube to create a private user to user chat.
https://www.youtube.com/watch?v=Ozrm_xftcjQ
Everything on the chat works accept that i keep getting this Error:
XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:
using firefox developer edition and chrome. if i click the stack trace link i get the following xml error:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /get_messages</pre>
</body>
</html>
but i have no GET calls at all..
The code looks as follows:
server.js file
var port = process.env.PORT || 3000;
//creating express instance
var express = require("express");
var app = express();
//creating http instance
var http = require("http").createServer(app);
//app.use(express.static(__dirname));
//creating socket instance
var io = require("socket.io")(http);
//create body parser instance
var bodyParser = require("body-parser");
app.use(bodyParser.json());
//enable url encode for POST requests
app.use(bodyParser.urlencoded({ extended : true }));
//create instance of mysql
var mysql = require('mysql');
//create mysql connection
// connectionLimit: 100,debug: true
var connection = mysql.createConnection({
host: 'localhost',
user: 'xxx',
password: 'xxx',
database: 'chatio'
});
connection.connect(function(error){
if(error){
console.log(error);
return;
}
console.log('database connected');
})
//enable header request for post requests
app.use(function(request, result, next){
result.setHeader("Access-Control-Allow-Origin", "*");
next();
})
//create api to return all messages
app.post("/get_messages", function(request, result){
console.log(request);
console.log(result);
connection.query("SELECT * FROM chat_messages WHERE (`from_id` = '"+request.body.sender+"' AND `to_id` = '"+request.body.receiver+"') OR (`from_id` = '"+request.body.receiver+"' AND `to_id` = '"+request.body.sender+"')", function(error, messages){
if(error){
console.log(error);
return;
}
console.log(messages);
//response will be in JSON
result.end(JSON.stringify(messages));
});
})
io.on("connection", function(socket){
socket.on("send_message", function(data){
//send event to receiver
var socketId = users[data.receiver];
io.to(socketId).emit("new_message", data);
//save in database
connection.query("INSERT INTO chat_messages (`from_id`,`to_id`,`message`) VALUES ('"+data.sender+"', '"+data.receiver+"', '"+data.message+"')", function(error, result){
if(error){
console.log(error);
return;
}
console.log('message saved');
});
})
})
http.listen(port, function(){
console.log("server started");
})
inde.php file code as follows:
//creating io connection
var io = io("http://localhost:3000");
var receiver = "johnny";
var sender = "steven";
function onUserSelected(){
$.ajax({
url: "http://localhost:3000/get_messages",
method:"POST",
cache: false,
data: {
"sender" : sender,
"receiver" : receiver
},
dataType: "json",
success: function(response){
var messages = response; //JSON.parse();
var html = "";
for(var i = 0; i < messages.length; i++){
html += "<li>" +messages[i].from_id + " says: " + messages[i].message + "</li>";
document.getElementById('messages').innerHTML += html;
}
}
});
return;
}
}
i figured it out..
the problem comes from this line:
result.end(JSON.stringify(messages));
I dont exactly understand why, but i changed it to
result.send(JSON.stringify(messages));
and now the bug is gone

NodeJS reload page but don't send user data again [duplicate]

This question already has answers here:
How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
(21 answers)
Closed 4 years ago.
I have a Node Js local server and several identical html pages. On every page I save some user data input fields saved simply on a text file. My problem is that if the users refresh the page the data from the previous html page is send again and again saved on the text file. Is there a way to prevent this?
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + "/public"));
app.use('/images', express.static(__dirname +'/images'));
app.listen(port, function(){
console.log('server is running on ' + port);
});
app.get('/', function(req, res){
res.sendfile('intro.html');
});
app.post('/userID', function(req, res){
//save the userID on a text file
var userID= req.body.userID + ';';
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
return res.sendfile('main.html');
});
app.post('/submit', function(req, res){
res.sendfile('main2.html');
});
Furthermore, I have also a refresh button that does the same as the browser refresh button. I s there a way to avoid the same problem?
<button>Reset</button>
and its JavaScript:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', clickHandler);
});
function clickHandler(element) {
location.reload();
}
Thank you in advance!
You can use fs.readFile and check if that file contain that userId
If that is not present then append or else dont append
fs.readFile('temporary/userID.txt', function (err, fileData) {
if (err) throw err;
if(fileData.indexOf(userID) == -1){
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
}
});
So, the code will be:
app.post('/userID', function(req, res){
//save the userID on a text file
var userID= req.body.userID + ';';
fs.readFile('temporary/userID.txt', function (err, fileData) {
if (err) throw err;
if(fileData.indexOf(userID) == -1){
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
}
});
return res.sendfile('main.html');
});

Res.write is not working when continuously sending UDP packet

//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express'), fs= require('fs'),path = require('path'),util = require('util'),dgram= require('dgram'),client= dgram.createSocket('udp4'),bodyParser = require('body-parser'),app = express(), ejs = require('ejs');
var plotly = require('plotly')("Patidar", "ku0sisuxfm")
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(express.static('public'));
//Reading in the html file for input page
app.get('/', function(req, res){
var html = fs.readFileSync('index2.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//reading in html file for output page
app.get('/output', function(req, res){
var html = fs.readFileSync('index4.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//Recieving UDP message
app.post('/output', function(req, res){
var once= req.body.submit;
if (once == "Once") {
//Define the host and port values of UDP
var HOST= req.body.ip;
var PORT= req.body.port;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) throw err;
});
//Recieving message back and printing it out to webpage
client.on('message', function (message) {
fs.readFile('index3.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var temp = message.toString(); //here you assign temp variable with needed value
var renderedHtml = ejs.render(content, {temp:temp, host: HOST, port: PORT}); //get redered HTML code
res.end(renderedHtml);
//var data = [{x:[req.body.number], y:[temp], type: 'scatter'}];
//var layout = {fileopt : "overwrite", filename : "simple-node-example"};
//plotly.plot(data, layout, function (err, msg) {
//if (err) return console.log(err);
//console.log(msg);
//});
});
});
}
if (once == "continuous") {
var timesRun = 0;
var requestLoop = setInterval(function(){
timesRun += 1;
if(timesRun === 5){
clearInterval(requestLoop);
}
//Define the host and port values of UDP
var HOST= req.body.ip;
var PORT= req.body.port;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) throw err;
});
//Recieving message back and printing it out to webpage
client.on('message', function (message) {
fs.readFile('index3.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var temp = message.toString(); //here you assign temp variable with needed value
var renderedHtml = ejs.render(content, {temp:temp, host: HOST, port: PORT}); //get redered HTML code
res.write(renderedHtml);
//var data = [{x:[req.body.number], y:[temp], type: 'scatter'}];
//var layout = {fileopt : "overwrite", filename : "simple-node-example"};
//plotly.plot(data, layout, function (err, msg) {
//if (err) return console.log(err);
//console.log(msg);
//});
});
});
}, 10000);
}
});
//Setting up listening server
app.listen(3000, "192.168.0.136");
console.log('Listening at 192.168.0.136:3000');
I have two button, one button sends the UDP packet once, while a continuous button sends the same UDP packets every 10 seconds. However, when this button is pressed, res.write is repeating the entire output again. Look at the attached pic to see output[![enter image description here][1]][1]
After putting your code into an auto-code-formatter to make it readable, I can see that you are doing this:
client.on('message', function (message) { ...
inside of your app.post() handler. That means that every time your post handler is called, you add yet another client.on('message', ...) event handler. So, after it's called the 2nd time, you have two event handlers, after it's called the 3rd time, you have three and so on.
So, as soon as you have these duplicate, each will get called and you will get duplicate actions applied.
Your choices are to either:
Use .once() for the event handler so it is automatically removed after it fires.
Remove it manually after it fires or when you are done with it.
Add it once outside your app.post() handler so you never add duplicates.
Restructure the way your code works so it doesn't have this type of issue. For example, you have two different handlers for the same incoming message. This is a sign of very stateful code which is more complex to write properly. A better design that isn't stateful in that way would be simpler.

how do we pass the parameters to db via url in express js?

I'm trying to insert the value to db through html page & passing the value to url. But value has been inserted as null merely inserting the value from html page it's working but through url null value has been inserted.
var express=require('express');
var app=express();
var sql=require('mysql');
var createConnect=sql.createPool({
host:"localhost",
user:"root",
password:"",
database:"stud"
});
app.get('/',function(req,res){
createConnect.getConnection(function(err,row){
if(err) throw err;
res.send("connected");
console.log("connected");
});
});
app.use(express.static('public'));
app.get('/index.html', function(req,res){
res.sendFile(__dirname+"/"+"index.html");
});
app.get('/process1/:fname/:rno/:MobNO',function(req,res){
If I remove the data1 value is inserted to db but I want to inset the data through url and html page also.
var data1={
sname:req.params.fname,
regno:req.params.rno,
mobno:req.params.MobNo
};
var data={
sname:req.query.fname,
regno:req.query.rno,
mobno:req.query.MobNo
};
createConnect.query("INSERT INTO student set?",(data1,data), function(err,rows){
if(err) {
console.log("check your query",err);
}
res.send("hello ram");
});
});

node.js data fetch in json model error

I am new to node.js
I was just making an simple application
my data is inserting properly into the database as well as fetching also from the database
But the problem is when I am trying to access it in json model it is giving me error
var express = require('express');
/*
* body-parser is a piece of express middleware that
* reads a form's input and stores it as a javascript
* object accessible through `req.body`
*
* 'body-parser' must be installed (via `npm install --save body-parser`)
* For more info see: https://github.com/expressjs/body-parser
*/
var bodyParser = require('body-parser');
// create our app
var app = express();
// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser.urlencoded({ extended: true }));
// A browser's default method is 'GET', so this
// is the route that express uses when we visit
// our site initially.
app.get('/', function(req, res){
// The form's action is '/' and its method is 'POST',
// so the `app.post('/', ...` route will receive the
// result of our form
var html = '<form action="/" method="post">' +
'Enter your name:' +
'<input type="text" name="userName" placeholder="Put your name" />' +
'<br>' +'Enter your city:'+'<input type="text" name="userCity" placeholder="Put your city" />' +
'<br>' +'Enter your state:'+'<input type="text" name="userState" placeholder="Put your state" />' +
'<br>' +'Enter your country:'+'<input type="text" name="userCountry" placeholder="Put your country" />' +
'<br>' +
'<button type="submit">Submit</button>' +
'</form>';
res.send(html);
});
// This route receives the posted form.
// As explained above, usage of 'body-parser' means
// that `req.body` will be filled in with the form elements
app.post('/', function(req, res){
var userName = req.body.userName;
var userCity = req.body.userCity;
var userState = req.body.userState;
var userCountry = req.body.userCountry;
// var document = {userName:userName,userCity:userCity,userState:userState,userCountry:userCountry};
var html = 'Hello: ' + userName + '.<br>' +'City: ' + userCity + '.<br>'+'State: ' + userState + '.<br>'+'country: ' + userCountry + '.<br>'+
'Try again.';
// res.send(html);
//res.send(JSON.stringify(doc));
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = require('mongodb').MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
/* var userName = req.body.userName;
var userCity = req.body.userCity;
var userState = req.body.userState;
var userCountry = req.body.userCountry;
var document = {userName:userName, userCity:userCity,userState:userState,userCountry:userCountry};*/
// do some work here with the database.
var insertDocument = function(db, callback) {
db.collection('test').insertOne( {
"userName" :userName,
"userCity" : userCity,
"userState" : userState,
"userCountry" :userCountry ,
}, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the test collection.");
callback(result);
});
};
var findDocument = function(db, callback) {
var cursor =db.collection('test').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.log(doc);
// res.contentType('application/json');
res.send(JSON.stringify(doc));
/* app.get('/test', function(req, res, next) {
res.json(doc);
});*/
} else {
callback();
}
// res.send(JSON.stringify(doc));
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
findDocument(db, function() {
db.close();
});
});
});
/* var document = {name:"David", title:"About MongoDB"};
db.collection('test').insertOne(document, function(err, records) {
if (err) throw err;
console.log("Record added as "+records[0]._id);
});*/
//Close connection
// db.close();
}
});
});
app.listen(3000);
Please help me to get rid off the problem.
Thank you..
The error I am getting is cann't set headers after they are send
This kind of error usually means that you try using res.send(...) multiple times from the same route.
Here you can see that in your find document, you use a cursor.each, and send your result inside this cursor.each. This means that you send multiple results from the same route.
What you should do instead is having a variable that you use to store your result before sending it once everything is retrieved.