Display MySQL data using Node.js - javascript

I am making a small script where I enter form data into a database table when I press submit.
What I want to do is to show the added data on the next page i.e. app.post for /form
at the moment I am getting only a employee ......with salary ..... added
But I want to display the whole row of the data I just added.
Now, how do I do that?
here's the code for server.js which i use to run the app.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'employees'
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req,res){
res.sendFile(path.join(__dirname,'index.html'));
});
app.get('/add-employee.html',function(req,res){
res.sendFile(path.join(__dirname,'/add-employee.html'));
});
app.post('/add-employee.html',function(req,res){
res.status(200).send();
console.log('employee '+req.body.name + ' added');
});
connection.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
app.post('/form',function (req,res){
//employee details from add-employee.html page
var name=req.body.name;
var designation = req.body.designation;
var pan = req.body.pan;
var aadhar = req.body.aadhar;
var bank = req.body.bank;
var salary = req.body.salary;
var allowance = req.body.allowance;
var esi = req.body.esi;
var uan = req.body.uan;
var details = {name:name,designation:designation,pan:pan,aadhar:aadhar,
bank:bank,salary:salary,allowance:allowance,esi:esi,uan:uan};
var query = connection.query('INSERT INTO employee_details SET ?',details,function(err,result){
if(err){
console.log(err);
}
console.log(query.sql);
});
connection.query('SELECT * FROM employee_details',function(err,rows){
if(err) throw err;
console.log('Data received');
console.log(rows);
});
res.status(200).send('employee ' + name + 'with salary of '+salary+ ' added');
});
app.get('/add-company.html',function(req,res){
res.sendFile(path.join(__dirname,'/add-company.html'));
});
app.get('/style.css',function(req,res){
res.sendFile(path.join(__dirname,'/style.css'));
});
app.get('/main.js',function(req,res){
res.sendFile(path.join(__dirname,'/main.js'));
});
app.get('/cmain.js',function(req,res){
res.sendFile(path.join(__dirname,'/cmain.js'));
});
var port=8080;
app.listen(8080,function(req,res){
console.log(`Payroll app listening on port ${port}!` );
});
I am able to see the rows from the select query in the console.
But the problem Is I dont know how to display that on the page itself.
how do I do that?

connection.query('INSERT INTO employee_details SET ?',details,function(err,result){
if(err){
console.log(err);
}
else{
res.status(200).send(result);
}
});
Remove the below part this will send a result from where you called this api and you can display that result

You need to select after insert.
Pay attention to the queries are async.
var query = connection.query('INSERT INTO employee_details SET ?',details,function(err,result){
if(err){
console.log(err);
}
console.log(query.sql);
connection.query('SELECT * FROM employee_details',function(err,rows){
if(err) throw err;
console.log('Data received');
console.log(rows);
res.status(200).send('employee ' + name + 'with salary of '+salary+ ' added');
});
});

Related

How to send fs.stat details in JSON format to front end AngularJS as a response?

I want output that gets the listing of path and gets each file name with the associated file size. I get this output in the command prompt, but I want
node to store this record and send response to the controller.js file.
My folder structure is:
node_modules
public
->controllers
- controller.js
->index.html
server.js
Code of server.js i.e backend code Node.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
var dir ='';
var result = [];
app.post('/filelist', function (req,res){
console.log(req.body);
dir = req.body.name;
res.end();
});
app.get('/filelist', function (req, res) {
console.log("I received a GET request")
fs.exists(dir, (exists) => {
if (exists) {
console.log("file exist " + dir);
fs.readdir(dir,function(err, items){
if (err) {
return console.error(err);
}
for (var i=0; i<items.length; i++) {
var file = dir + '/' + items[i];
console.log(file);
fs.stat(file, generate_callback(file));
}
});
}
else {
console.error('myfile does not exist');
res.json({message: 'Requested "'+dir+'" file or folder does not exist!'
});
}
});
function generate_callback(file) {
return function(err, stats) {
result = ({name:file.substring(6),Size:stats["size"]});
console.log(result);
res.json(result);
}
};
});
app.listen(3000);
console.log("Server running on port 3000");
controller.js
function AppCtrl($scope, $http){
console.log("Hello world from controller");
var refresh = function() {
$http.get('/filelist').success(function(response){
console.log("I got the data I requested");
$scope.filelist = response;
$scope.list = "";
$scope.msg = response.message;
});
};
$scope.searchPath = function() {
console.log($scope.contact);
$http.post('/filelist', $scope.list).success(function(response){
console.log(response);
refresh();
});
};
}
In the NodeJS code, don't call res.json() until processing each file. One way to do this is to pass the number of files in the directory to the callback function -
for (var i=0; i<items.length; i++) {
var file = dir + '/' + items[i];
console.log(file);
// pass the number of items in the directory to the callback here
fs.stat(file, generate_callback(file,items.length));
}
Then in the callback, add the results of each file to an array (e.g. var results) and when the length property of that array is equal to the number of items in the directory, call res.json():
var results = [];
function generate_callback(file,numberOfItems) {
return function(err, stats) {
result = ({name:file.substring(0,6),Size:stats["size"]});
results.push(result);//add the result for the current file to the list of results
//when we have reached the last file, send the results in JSON format
if (results.length == numberOfItems){
res.json(results);
}
}
};
I have this running on codeenv.com - see the angular page utilizing the nodeJS filelist endpoint here - if that stops working, you should be able to open the environment, click the Launch button in the upper right corner of the screen, and then in the terminal run node server.js to start the server.

Node JS: Convert retrieved data from DB as JSON to Plain text

In the following code, data are retrieved from a database into JSON. What I would like to do is to display each single data as a plain text:
var http = require("http");
var mysql = require('mysql');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/Search.html', function (req, res) {
res.sendFile( __dirname + "/" + "Search.html" );
})
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : 'passpass',
database : 'SocialQuery',
}
);
connection.connect();
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
SearchType:req.body.SearchTypes,
Term:req.body.term
};
//var vas = JSON.stringify(response);
var search = req.body.SearchTypes;
var term = req.body.term;
var queryString;
if(search == 'Author')
{
queryString = 'Select Label,TDate from Tweet where AuthorID IN (select ID from Author where Lable = ?)';
}
else if(search == 'Mention')
{
queryString = 'select Tweet.Label, Tweet.TDate, Author.Lable from Tweet, Author where Tweet.ID IN (select TweetID from TweetMention where MentionID IN (select ID from Mention where Label = ?)) AND Author.ID = Tweet.AuthorID'
}
var query = connection.query(queryString, [term], function(err, rows) {
console.log(rows);
var tweet = JSON.stringify(rows);
res.write("Author: " + tweet.Lable);
res.write("Date: " + tweet.TDate);
res.end();
});
console.log(query.sql);
})
//}).listen(8081);
http.createServer(app).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
When I print the data using res.write(JSON.stringify(rows)); I got the following:
[{"Label":"lest play hero","TDate":"2016-03-12T00:00:00.000Z","Lable":"esti_jony"},{"Label":"u r the best ! Ill always keep","TDate":"2016-03-08T00:00:00.000Z","Lable":"adam03cooper03"}]
but when I run the code above, I got:
Author: undefined Date: undefined
What I understood is the problem because two rows of data have been retrieved and I do not know how to let it display each author (Lable) and each date (TDate).
You're converting a javascript object to a JSON string and then trying to access the javascript object's properties on the string. That won't work. You want to use the javascript object instead, but since there is more than one row, you will have to either choose which one you want to respond with or write all rows or whatever your use case calls for.
For example:
var query = connection.query(queryString, [term], function(err, rows) {
if (err) throw err;
for (var i = 0; i < rows.length; ++i) {
var tweet = rows[i];
res.write("\nAuthor: " + tweet.Lable);
res.write("\nDate: " + tweet.TDate);
if (i + 1 < rows.length)
res.write('\n');
}
res.end();
});

Have set up mongodb, mongoose etc but when I try and add something to the database it doesn't actually add it

I'm using localhost and have all the modules set up correctly and I've checked that the database exists. When I type in localhost:3000/pods/add?firstName='John' it's supposed to add it to the database, but for some reason it isn't working.
var express = require('express');
var _ = require('underscore');
var mongoose = require('mongoose');
var podStore = require('./lib/pod-handler.js');
var podsLibrary = require('./lib/pods-library.js');
var podList = [];
var mongoPort = 27017;
var app = express();
var port = 3000;
var router = express.Router();
var pods = podsLibrary.list();
mongoose.connect('mongodb://localhost:'+mongoPort+'/pods');
router.route('/').get(function(request, response) {
//console.log('You hit an empty URL .. :(');
response.status(503).send("Service Unavailable");
});
router.route('/lib').get(function(request, response) {
//console.log('You hit an empty URL .. :(');
response.status(200).send("Cool beans!");
});
router.route('/pods/list').get(function(request, response){
if(!pods){
return response.status(503).send("Service Unavailable");
}
return response.status(200).send(makeReadableList(pods));
function makeReadableList(pods){
var podsHtml = " ";
_.each(pods, function(value, key){podsHtml = podsHtml + key});
return podsHtml;
}
});
router.route('/pods/add').post(function(request, response){
if (!request.query){
return response.status(400).send("Please give first name");
}
var payload = request.query;
if (!payload.firstName){
return response.status(400).send("give name");
}
podStore.save({
firstName: payload.firstName,
lastName: payload.lastName
}, function(){
return response.status(200).send(payload.firstName + " has been added!");
var space = " ";
_.each(pods, function(value, key) {
key + space;
return space + payload.firstName + payload.secondName;
});
});
});
router.route('/pods').get(function(request, response) {
//console.log("We reached the POD page -- Yay! :D");
response.status(200).send("Server unavailable");
});
app.use('/', router);
app.listen(port, function () {
console.log('App listening on port %s', port);
});
I've checked over my code countless times and I can't seem to find the problem.
Here's the pod-handler file.
var PodDoc = require('../models/pods.js');
module.exports = {
save: save
}
function save(pod, callback){
var podToSave = new PodDoc();
podToSave.firstName = pod.firstName;
podToSave.lastName = pod.lastName;
/*podToSave.skills = pod.skills;
podToSave.avatarUrl = pod.avatarUrl;
podToSave.address = {
number: pod.address.number,
lineOne: pod.address.lineOne,
lineTwo: pod.address.lineTwo,
postcode: pod.address.postcode
}
podToSave.phoneNumbers = {
mobile: pod.phoneNumbers.mobile,
landline: pod.phoneNumbers.landline
}*/
podToSave.save(function(err){
if(err){
console.log(err);
} else {
console.log("Working");
callback();
}
})
}
When I type in localhost:3000/pods/add?firstName='John' it's supposed to add it to the database
If i understand correctly, you want to open this url in browser, and expect to have a record John in database.
Change router request type to GET, this
router.route('/pods/add').post(/*omitted*/);
to this
router.route('/pods/add').get(/*omitted*/);
Server is expecting POST request, but browser cannot handle it without FORM element or ajax request, browsers usually uses GET request, i mean when you open your url, it send GET request to server
There may be a typo error as in the url you are using port 300 where as the port configured for localhost is 3000.
When I type in localhost:300/pods/add?firstName='John'

How to get response from other user after joining room using socket.io

i have one doubt regarding socket.io.I have two type of user i.e-admin,client .First admin will create userid and join to the room.I need when user will join room the admin should get response and need help regarding this.
My working codes are given below.
server.js:
var port=8888;
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var database='Oditek';
var collections=['video'];
var app= express();
var server=http.Server(app);
var io=require('socket.io')(server);
var db = mongo.connect("127.0.0.1:27017/"+database, collections);
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT
db.on('ready', function () {
console.log('database connected')
});
app.get('/',function(req,res){
res.sendfile('view/login.html');
});
app.post('/login',function(req,res){
var username=req.body.username;
var password=req.body.userpassword;
if(username && password){
db.video.findOne({
username:username,
password:password
},function(err,doc){
if(doc){
console.log('login',doc);
res.send(doc);
}
if(err){
console.log('login12',err);
res.send("could not login");
}
});
}
});
app.get('/video',function(req,res){
res.sendfile('view/video.html');
});
//socket----programming//
var roomid;
io.on('connection',function(socket){
//console.log(socket);
roomid=socket.handshake.query.roomid;
var usertype=socket.handshake.query.usertype;
socket.join(roomid);
});
server.listen(port);
console.log('server is listening on the port'+port);
My client side code is given below.
function videoBroadCasting(uType){
var messageGateWay;
if(uType=='admin'){
var userid = getRandomString();
$('#styled').val('http://localhost:8888/video?usertype=client & id='+userid);
messageGateWay=io('http://localhost:8888/?roomid='+userid+'usertype='+uType);
}
if(uType=='user'){
messageGateWay=io('http://localhost:8888/?usertype='+uType);
}
messageGateWay.on('connect',function(){
console.log('socket get connected');
});
}
function getRandomString() {
return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
}
function getQuery(key){
var temp = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"));
if(!temp) return;
return temp[1];
}
After client is joining the room the admin should get one notification.Please help me to do this.
One simple solution is to save the socket object from the admin in the server when the admin joins the room. Then, when some other user join the room, simply emit a message to that socket from the admin/admins. Just keep an array update with the admins actually logged in the room.
Something like:
var socketAdmin = {};
io.on('adminJoins',function(socket){
socketAdmin = socket;
roomid=socket.handshake.query.roomid;
var usertype=socket.handshake.query.usertype;
socket.join(roomid);
});
io.on('clientJoins',function(socket){
roomid=socket.handshake.query.roomid;
socketAdmin.emit('newClient', {socketClient: socket, roomId: roomid};
var usertype=socket.handshake.query.usertype;
socket.join(roomid);
});
In this example, the client sends a message 'adminJoins' if you are an admin, or 'clientJoins' ir you are a client, you can send that checking the uType var you have. In case a new client joins the room, the admin recieve a 'newClient' message with the socket of the client and the roomId (just an example).

How can I set req.session from this scope?

I'm writing a Node.js application using Express and a PostgreSQL database using node-postgres. I want to look up the current user's username and real name based on their email, and set them in req.session. However, if I set them where I am in the code below, they are undefined when we leave that block (i.e. the first console.log statements print the correct info, the second set prints undefined. How can I solve this?
var client = new pg.Client(app.conString);
var realname = "";
var username = "";
client.connect();
var query = client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email]
);
query.on('row', function(row) {
req.session.realname = row.realname;
req.session.username = row.username;
console.log(req.session.realname);
console.log(req.session.username);
});
console.log(req.session.realname);
console.log(req.session.username);
query.on('end', function() {
client.end();
});
The second pair of console.log will execute before the query-results are available (in the row event handler).
If your code is going to be used in an Express route, you would use something like this:
app.get('/', function(req, res) {
var client = new pg.Client(app.conString);
var realname = "";
var username = "";
client.connect();
var query = client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email]
);
query.on('row', function(row) {
req.session.realname = row.realname;
req.session.username = row.username;
});
query.on('end', function() {
client.end();
res.send(...); // <-- end the request by sending back a response
});
});
An alternative for using the EventEmitter interface for node-postgres would be to just pass a callback to query (which looks better with Express IMHO):
client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email],
function(err, results) {
if (err)
// handle error
else
if (results.length)
{
req.session.realname = results[0].realname;
req.session.username = results[0].username;
}
res.send(...); // done
});

Categories

Resources