I am new to node and meteor.js. I am trying to wrap my head around some of the basic functionality coming from PHP/MYSQL.
I am trying to work with the node npm MYSQL to output a list of data to a template file, but can't seem to get the data to connect to the template. I can get the data to output to console.log - but not to the template.
Here is my server connection.
var eventName = [];
if (Meteor.isServer) {
Meteor.methods({
'geteventName': function () {
this.unblock();
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
socketPath : '...socketpath',
database : 'database'
});
connection.connect();
connection.query('SELECT eventName FROM events', function(err, rows, fields) {
if (err) throw err;
for (var i = 0; i < rows.length; i++) {
eventName.push(rows[i]);
};
//console.log(eventName);
return eventName;
});
connection.end();
//return "some return value";
}
});
}
if (Meteor.isClient) {
Meteor.call('geteventName', function (error, result) {
console.log(result);
});
}
** I have updated the code based on the comments, but the Meteor call just returns undefined. If I set a general variable to return - i.e. I just had it set to some dummy text, the results passes through to the client and returns in the console.
Related
I encountered a weird bug when doing a quick coding assignment.
Here is my code.
Lets call this 'A'
//Grab all the animals from the database
WebApp.get('/all',(req,res) =>
{
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const query = "SELECT * FROM animals";
connection.query(query, (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
and this 'B'
//Grab a selected animal from the database given a valid Id.
WebApp.get('/:id',(req,res) =>
{
console.log("Fetching user with id: " + req.params.id);
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const animalId = req.params.id;
const query = "SELECT * FROM animals WHERE id = ?";
connection.query(query, [animalId], (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
For some reason, if I put A before B it works, and I get successful results from my queries. However, if I put B before A, B will return successfully, but A will return '[]'. Anyone know why?
Thanks for any help!
Have you tried terminating the connection after each request, or considered using a connection pool? I am not familiar with nodeJS integration with MySQL, but in SQLServer, it is best to use ConnectionPool, when asynchronously making database requests.
I'm new in Node JS and I'm trying to display the fetched data from my MySQL Table into a table in my HTML-File. But I couldn't find anything that helped me. I would really appreciate it if somebody can help me to get a solution! :)
Here's my js-code:
//app.js
// Get the mysql service
var mysql = require('mysql');
var express = require('express');
var app = express();
app.get('/', function (request , response) {
fetchData(response);
console.log('Done. Displayed Data.');
});
// Add the credentials to access your database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'Breunninger',
port: '3306'
});
// connect to mysql
connection.connect(function(err) {
if(err){throw err;}
console.log('Connected');
});
function executeQuery(sql, cb){
connection.query(sql, function( result, fields){
cb(result);
})
}
function fetchData(response){
executeQuery("SELECT username, tor, datum, sendungsstruktur FROM Buchung JOIN user ON(user.id = Buchung.userid)", function (result) {
console.log(result);
response.write('<div class="container-wrap"><table id="example" class="display"><tr>');
for(var column in result[0]){
response.write('<td> <label>' + column + '</label></td>');
response.write('</tr>');
}
for(var row in result){
response.write('<tr>');
for(var column in result[row]){
response.write('<td>' + result[row][column]+ '</td>');
}
response.write('</tr>');
}
response.end('</table></div>');
});
}
<div class="container-wrap">
<div class="flexslider">
<script src="app.js"></script>
</div>
</div>
There's a small (but critical!) error in the executeQuery function, the first argument should be the error object, so if you can re-write this as below your query should work.
function executeQuery(sql, cb){
connection.query(sql, function( error, result, fields){
if (error) {
console.error("An error has occurred:", error);
} else {
cb(result);
}
})
}
Node callback usually reserve the first argument for an error object, it's easy to miss this!
Also, we should be clear, the Node.js Express code will be running on the server side, so to see the results you need to point your browser to the host and port this is serving, e.g. http://localhost:3000/ (if you do:)
app.listen(3000);
I am still new to nodejs and Javascript, I am sorry if my question appear to be very simple but I am struggling a lot and I can't seem to find an answer on the net.
What I want to do is basically calling a script (sqlRequest.js) and send an integer while calling it. This script will send an sql request to my database and will return the result (an object) to the original file.
Here are the codes:
router.post('/request', function(req, res, next){
var id = req.body.id;
var essai = require('./sqlRequest.js');
console.log("INDEX: "+essai.sendSQL(id)); });
And now the sqlRequest.js code:
exports.sendSQL = function(id) {
var mysql= require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'bcombes',
password : 'bertrand1994',
database : 'totalkpi'
});
connection.connect();
var sql ="SELECT * FROM tra_ticket where id=?";
var insert=[id];
sql=mysql.format(sql, insert);
connection.query(sql, function(err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
return rows;
}
});};
On the console I can see that the console.log("INDEX: "+essai.sendSQL(id)); appears to be undefined and is displayed before the console.log(rows).
Is it possible that the server does not wait for the function to finish and display the variable anyway ?
Anyway thank you for taking the time to help.
Your logic to pass a variable between files is fine. The reason your seeing essai.sendSQL(id) return undefined is because connection.query(...) is called asynchronously and, as you've mentioned in your question, the console.log fires before the DB query completes.
To fix that issue you just need to refactor your code slightly:
var essai = require('./sqlRequest.js');
router.post('/request', function(req, res, next){
var id = req.body.id;
// send callback to sendSQL
essai.sendSQL(id, function(index) {
// this will only fire once the callback has been called
console.log("INDEX: " + index)
})
});
And then in sqlRequest.js:
exports.sendSQL = function (id, cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'bcombes',
password: 'bertrand1994',
database: 'totalkpi'
});
connection.connect();
var sql = "SELECT * FROM tra_ticket where id=?";
var insert = [id];
sql = mysql.format(sql, insert);
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
// call the callback
cb(rows);
}
});
};
Following is the Server.js File, here I am Fetching The Details From Table which working Good. I need to Get a Variable From k.php which is in the Same Folder.Iam using npm exec-php module to get the Values From Php File. But The Variable is Showing Undefined.
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
express=require('express'),
session=require('express-session'),
mysql = require('mysql'),
execPhp = require('exec-php'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test',
port: 3306
}),
POLLING_INTERVAL = 3000,
pollingTimer;
// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
if (err) {
console.log(err);
}
});
// creating the server ( localhost:8000 )
app.listen(8000);
// on server started we can load our client.html page
function handler(req, res) {
fs.readFile(__dirname + '/client.php', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.php');
}
res.writeHead(200);
res.end(data);
});
}
execPhp('k.php', function(error, php, outprint){
// Here I expected The outprint Will be 'One' but it print undefined
console.log(outprint);
php.my_function(1, 2, function(err, result, output, printed){
//this my_function is also showing Error
});
});
var pollingLoop = function() {
// Doing the database query
var query = connection.query('SELECT * FROM users where user_id=1'),
users = []; // this array will contain the result of our db query
// setting the query listeners
query
.on('error', function(err) {
// Handle error, and 'end' event will be emitted after this as well
console.log(err);
updateSockets(err);
})
.on('result', function(user) {
// it fills our array looping on each user row inside the db
users.push(user);
})
.on('end', function() {
// loop on itself only if there are sockets still connected
if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
updateSockets({
users: users
});
} else {
console.log('The server timer was stopped because there are no more socket connections on the app')
}
});
};
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
console.log('Number of connections:' + connectionsArray.length);
// starting the loop only if at least there is one user connected
if (!connectionsArray.length) {
pollingLoop();
}
socket.on('disconnect', function() {
var socketIndex = connectionsArray.indexOf(socket);
console.log('socketID = %s got disconnected', socketIndex);
if (~socketIndex) {
connectionsArray.splice(socketIndex, 1);
}
});
console.log('A new socket is connected!');
connectionsArray.push(socket);
});
var updateSockets = function(data) {
// adding the time of the last update
data.time = new Date();
console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
// sending new data to all the sockets connected
connectionsArray.forEach(function(tmpSocket) {
tmpSocket.volatile.emit('notification', data);
});
};
console.log('Please use your browser to navigate to http://localhost:8000');
the main Problem is in these Lines
execPhp('k.php', function(error, php, outprint){
// Here I expected The outprint Will be 'One' but it print undefined
console.log(outprint);
php.my_function(1, 2, function(err, result, output, printed){
//this my_function is also showing Error
});
});
The Following is k.php in the same folder
<?php
echo "One";
function my_function($arg1, $arg2){
echo "Two";
return $arg1 + $arg2;
}
?>
This is the Error
I've got two node.js files: server.js and database.js. I want my socket.io emitting to happen in server.js and the database queries in database.js. Server.js:
// init
io.sockets.on('connection', function(socket) {
initdb = db.initdb();
console.log(initdb)
});
My database.js contains basically the following code:
function query(queryString) {
connection = mysql.createConnection({
host: '12.23.45.67',
user: 'user',
password: 'password',
database: 'database'
});
connection.connect();
var res = connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
});
connection.end();
}
// export initdb for external usage by server.js
exports.initdb = function() {
var initdb = query("SELECT * FROM columns;");
};
My problem is that I want the rows object from within the connection.query function to be returned to my initdb function. However the only place where I can log this object is within that function. How can I pass the query results so I can emit the JSON object it from server.js?
Remember that node is asynchronous. So for the most part, you get data back through callbacks rather than as return values to functions.
You'll need to chain a callback through to where your query happens, something like:
// in database.js
exports.initdb = function(cb) {
query("SELECT * FROM columns", cb)
}
function query(queryString, cb) {
// .. stuff omitted
var res = connection.query(queryString, function(err, rows, fields) {
connection.end();
if (err) return cb(err);
cb(null,rows);
});
// in server.js
io.sockets.on('connection', function(socket) {
db.initdb(function(err,rows) {
if (err) {
// do something with the error
} else {
console.log(rows)
}
});
});
The callback would be a function taking 2 parameters, err and rows. Your server.js code would need to check the value of err and act accordingly, otherwise it would have the rows.