I'm relatively new to Node JS. I'm attempting to query the database, and then simply emit that data to the front end using socket.io, however I've noticed that it is intermittently sending the data / not sending the data to the front end. I'm assuming that the reason behind this is because the query has not yet finished yet, and was wondering how you'd wait for the result to be accessible before continuing?
I'm using npm mysql to access the database within the socket such as below:
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : '',
database : 'db'
}
);
Here is my query:
connection.query(queryString, function(err, result, fields){
if(err) throw err;
socket.emit('emitFunction', result);
});
The callback only called after query done so the result should available inside the callback function. Log both err and result to see what happened
Related
Can someone explain or point to some tutorial where is explained how to render rows of data from mySql database into react.js component?
I've made small database using mysql workbench and this baza.js file inside my project folder:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'db'
});
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM promjer", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
When I run node baza.js in my CMD, everything seems fine, I get everything from that specific table inside CMD terminal so I guess my database is ok and it's connected with app.
What troubles me is how to render that data inside my app?
I know that React by itself can't handle data so i should use Express.js. But I don't get what to do with it. Express should be running on other port so how should I even get data to component in app which is running on port 3000 if express is running on port 9000?
Thanks in advance!
I am building an application that has a backend that uses SQL queries to get data from a SQL Server database. However, I need to write a query that truncates and repopulates a table in that database using data from a second database. Here is what my code looks like:
// establishes a connection to serverName and uses DB1 as the database. But how can you access two?
global.config = {
user: 'username',
password: 'password',
server: 'serverName',
database: 'DB1'
};
// run this query. It's already been tested in SQL server and works fine there
let query = "TRUNCATE TABLE [DB1].[dbo].[Shop]; INSERT INTO [DB1].[dbo].[Shop] (Shop, shopDescription, Address, City)" +
" SELECT Shop, Description, Address, City FROM [DB2].[dbo].[ShopTable]"
new sql.ConnectionPool(config).connect().then(pool => {
return pool.request().query(query) }).then(
result => {
console.log(result.recordset)
//result returns as "undefined"
res.setHeader('Access-Control-Allow-Origin', '*')
res.status(200);
sql.close();
}).catch(err => { //error is not thrown
res.status(500).send({ message: err})
sql.close();
});
I get an "undefined" result, and find that no update to the table was made. The issue here isn't exactly clear whether it can't reach the table in DB2, or if perhaps the command doesn't work with the Node.js mssql package?
It appears this was a front end to back end connection issue. I was able to get the query to work without any changes to the database information, so it appears I can access the second database without any issues.
component.ts
this.httpService.patch('update', {} ).subscribe()
index.js
app.patch('/api/update', controllers.manualQueries.update);
Github repo. I am trying to use MongoDB Atlas database with my node JS Login & Signup app for storing data. The problem is that the data is not saving to the database or in other words the request isn't going through even if my app is connected to Atlas. Full code available on www.github.com/tahseen09/login
// Connection to mongodb atlas
const uri = "mongodb+srv://tahseen09:<PASSWORD>#cluster0-pirty.mongodb.net/userdb"
MongoClient.connect(uri, function(err, client) {
if(err) {
console.log('Error occurred while connecting to MongoDB Atlas...\n',err);
}
console.log('Connected to Atlas');
const collection = client.db("userdb").collection("credentials");
client.close();
});
//New User Registration
app.post('/register', function(req,res){
var cred= new credential();
cred.uname=req.body.uname;
const hash = bcrypt.hashSync(req.body.password, 10);
cred.password=hash;
collection.save(function(err,newuser){
if(err){
res.status(500).send("Username exists");
}
else{
res.status(200).send("New User Created");
}
})
})
The code that is important is attached as a snippet and the rest of the code is available on www.github.com/tahseen09/login
Note: I am running this app on localhost.
Let me describe your flow so you can understand wrong point there :)
Connect to MongoDB
Create reference to the collection
Close connection
When someone tries to access /register route, you already have closed connection by that time. Thus, any operation attempt to the database will end up with connection error.
From the documentation it's recommended calling MongoClient.connect once and reusing the database variable returned by the callback, i.e. do not close connection manually, driver will just create and use pool of connections, so don't worry about closing connection. Check out example code in the documentation.
Lets step through the code to see what happens:
MongoClient.connect(uri, function(err, client) {
A connection to mongodb is created, then somewhen the connection is established or it fails, then the callback gets called back. Now you create a local variable holding the database reference:
const collection = client.db("userdb").collection("credentials");
And then you close the connection:
client.close();
Then the callback ends:
});
which means that a variables inside (connection) can't be accessed anymore and get therefore recycled.
Now somewhen (that might even happen before the db connection gets established), someone requests the webpage and you try to do:
collection.save(/*...*/);
That won't work for various reasons:
1) The db might not even be opened
2) If it was opened already, it was also closed already.
3) Even if it is open at the moment, you still cannot access connection as it is not in scope.
Now to resolve that we have to:
1) only start the webserver when the db connection is establishee
2) don't close the connection
3) expose the connection so that it can be used elsewhere
For that it makes sense to create a function that establishes the connection and calls back with the db:
function withCredentials(callback) {
const uri = "mongodb+srv://tahseen09:<PASSWORD>#cluster0-pirty.mongodb.net/userdb"
MongoClient.connect(uri, function(err, client) {
if(err) {
console.log('Error occurred while connecting to MongoDB Atlas...\n',err);
} else {
console.log('Connected to Atlas');
const collection = client.db("userdb").collection("credentials");
callback(collection);
}
});
}
So now you can use that:
withCredentials(function(credentials) {
app.post('/register', function(req,res){
const cred = { };
cred.uname = req.body.uname;
cred.password = bcrypt.hashSync(req.body.password, 10);
credentials.insertOne(cred, function(err,newuser){
if(err){
res.status(500).send("Username exists");
} else {
res.status(200).send("New User Created");
}
})
});
});
I am new to Node.JS and AngularJS and I have made a connection to a database using Node.js (code below)
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodetest'
});
connection.connect();
connection.query('SELECT * from testtable', function(err, rows, fields) {
if (!err) {
var test = rows;
console.log('The solution is: ', test);
return test;
} else{
console.log('Error while performing Query.');
}
});
connection.end();
the database consists of 2 tables (ID and name) and only has 1 row (1, 'Luuk')
my code gets put through Grunt for compiling.
when I run the script stated above, it give the expected result (The solution is: [ RowDataPacket { ID: 1, name: 'Luuk' } ])
but when I want to add this to a controller in angularjs, it gives no results
app.controller('NameController', function() {
this.nameList = test;
});
how would be fixed?
I think that you're confusing concepts.
Angular.js and Node.js are running in a COMPLETELY different environment. Node.js is a server, that is running locally in your machine, which you can access via browser with the url localhost:3000 for example. But this server can be running on another machine for example, which you would be able to access via IP, something like 123.4.5.678:3000.
To share data between the backend and the frontend, you must do this over requests. When you access the localhost via browser, you're doing a request to the server, and the server provide some response, like a HTML page or something like that.
Look this example at the Nodejs Docs
http.createServer( function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(3000);
In the response we are returning a plain text. But this can be json, with your search at the database.
And you can do a specific route, like /getTestTable which you can call in the Angular, with the $http service, and handle this.
I suggest to take a better look at how Node.js works, and Angular.js too.
You would like to take a look too at the Express.js, a framework for Node.
Check the scope of variable test - it is defined inside call back function of connection.query. Try defining variable 'test' globally.
When i run my node.js script i get this error:
http://i.gyazo.com/4abc4f518db0de3cb36e34a9fa163e22.png
I was reading a similar error and the guy said it was because the script wasn't connecting to the mysql database. I've tried all of the different logins i can think of and it still wont work. I have tried connecting with no credentials and i get the same error. These are the current credentials i am using to log in:
host : 'localhost',
user : 'root',
password : 'mypassword',
database : 'milky',
The code where the error comes from:
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'maxitems\'', function(err, row, fields) {
if(offer.items_to_receive.length > row[0].value) {
offers.declineOffer({tradeOfferId: offer.tradeofferid});
offer.items_to_receive = [];
mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`) VALUES (\''+offer.steamid_other+'\',\'toomuch\',\'System\')', function(err, row, fields) {});
return;