First of all, today is my first time that i worked with node.js. So, excuse me if my questions are very simple for you.
I'm writing you because i can't find similar solutions to my problem.
I want to press an html button and then i want to trigger my test.js file.
Do you know if i can insert the following code inside my js file? Is there an another way that we run the node.js files inside html?
Here is my code: (by the way is right the window redirection??)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "",
database: "testaki1"
});
con.connect(function(err) {
if (err) throw err;
var someVar = [];
con.query("SELECT site_id FROM testaki12 WHERE user_id = '5'", function (err, rows) {
if (err){
throw err;
}
else {
setValue(rows);
}
});
function setValue(value) {
someVar = value;
console.log(someVar);
}
if (someVar == 1)
{
res.send('<script>window.location.href="https://www.google.gr/?hl=el";</script>');
}
});
Related
I'm trying to connect to a MySQL database using React and Node, and I created a database class to act as a singleton to get the connection to the database, but then it gives me the following error:
TypeError: Net.createConnection is not a function
I've done some searching and the main search results I can see are that the code is rendering client side, which doesn't completely make sense to me, considering I'm running this on node js through npm start.
let con = null;
class Database
{
}
Database.prototype.connection = function()
{
if(con!=null) {
return con;
}
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
return con;
}
export default Database;
I apologize if I don't know the correct terminology.
Error I see in the browser
I'm trying to use the mysql module to get some data from a mysql database and then write it to an HTML page but it seems stuck inside the query function itself.
The code looks like this:
rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
var rooms = result;
console.log(rooms[9]);
});
});
console.log(rooms);
The first console.log outputs the results properly, but the second one returns the empty array as declared in the first line and prints first. I'm new to Javascript so I'm probably missing something very obvious. Thanks in advance.
I think you are recreating another variable because adding "var " before. Have you tried without it?
If it doesn't work, here another posible solution:
global.rooms = [];
global.rooms = result;
https://nodejs.org/api/globals.html#globals_global
var rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
rooms = result;
console.log(rooms[9]);
});
});
console.log(rooms);
you missed out to declare rooms as global variable.
approach using a callback function
rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
function query(callback) {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
var rooms = result;
callback(rooms);
console.log(rooms[9]);
});
});
}
function log_it_out() {
console.log(rooms);
}
query(log_it_out);
I don't think it matters for you anymore since it's been roughly a year since you asked this basic question, however maybe someone else that searches for this question might find this information helpful since I had the same problem.
**} else if(req.url === "/api/labeat") {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(information));**
IMPORTANT
When you try to return something to a website beside the variable declarations, when you use res.end();, make sure to turn the result or whatever kind of information you're trying to work with into a string or buffer since the res.end() expects either a string or a buffer. Also specify the Content-Type as I did (application/json).
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);
}
});
};
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.
I have a simple file model.js like follows:
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
and in my web.js I load the model using model = require('./model.js'). One werid thing is that although I did not call model.connect(), the message "Connect to the database successfully" still got logged to my console. Why is this happening and is there a way to avoid it?
EDIT:Never mind I have found a workaround:
exports.connect = function(){
mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
}
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
You just called mongo.Db.connect() and assigned its result to exports.connect.
That code runs as soon as you require() the module.
Instead, you need to create a function:
exports.connect = function() { ... };