I am using NodeJs along with MySQL. I am using node-mysql after looking at MySQL with Node.js. Now the problem is I am trying to make db connection only once and using GETs inside it but it's not working.
Code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
app.get('/hello',function(req,res){
console.log('Hello');
res.send('Hi');
});
});
But the above code is not working. It is not recognizing the route. But making a connection inside every get function works.
I should be doing something wrong. Is there any way such that I can connect to the Db only once ?
You should move your call to app.get to the top level scope of the file. These calls are declarative and should be thought of more like configuring your application than the application's business logic. From the mysql docs, the connection object will automatically implicitly open a connection to the database if connection.query is called and a connection is not yet established. That sounds like the mechanism you should take advantage of.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
app.get('/hello',function(req,res){
console.log('Hello');
connection.query('select * from users', function (error, result) {
res.send('Hi');
});
});
Related
So i built a frontend where you can fill in a movie name, a review and submit it to a database. Now im trying to connect a mysql database i created to the index.js , so that it gets filled with the first entry. Im trying to accomplish it like this:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
But somehow the frontend gets the text ive send "Change done" but the database still doesnt show any entries. Any ideas where my mistake may be? Is it a code mistake or does it have to do with me db configuration. In mysql workbench i just created a default connection without changing anything.
EDIT: The Error seems to be the following:
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
EDIT:
The following comment here solved my problem:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.
I think you have an error in your code but you are not showing it as you don't test in err variable, try this code in order to show what error you are getting:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
if(err) {
console.log(err);
res.send(err.toString());
}
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
So as Med Amine Bejaoui pointed out in a comment, the solution is:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.
const mysql = require('mysql');
let connection = mysql.createConnection(...);
connection.connect((err)=>{
...
connection.query((err)=>{
...
connection.end();});
});
After I close the connection by using
connection.end()
, if I want to query the database again using the same credentials, do I need to make a new connection by calling
mysql.createConnection(...)
Or can I reuse the same connection by simply calling
connection.connect(...)
A little background: I'm deploying an angular/node.js app to a shared hosting website, and the web host has a maximum limit of 25 concurrent connections to mySQL database, therefore I need to make sure I close a connection properly after a user does his query. I am not sure if I could reuse the connection created by mysql.createConnection(...) after I close that connection, or do I need to create a brand new connection.
You can use one global connection for getting data from db .
If You working on single file than you can write as
app.js one file only
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
});
if you want to use same connection in multiple file than you can write as
app.js
app.use(
connection(mysql, {
host: xxxxx,
user: 'root',
password : xxxx,
port : 3306,
database:dbname
},'pool'),
);
var oem = require('./routes/type');
app.get('/api/oemtype',oem.type);
For the second file
type.js
exports.type = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM type',function(err,rows)
{
if(err)
res.json({
status:0
});
res.send(rows);
res.render('customers',{page_title:"Customers - Node.js",data:rows});
});
});
};
No need to use of connection.end().
Currently I dont use connection pooling on my settings since i only have 1-4 users in the application.
According to the doc this is the recommended way.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
Now, what i did was export the connection object and shared it to other api resources.
On db.js file
var mysql = require('mysql');
var connection = mysql.createConnection({ ... });
module.exports = connection;
On api.js file
const express = require('express');
const router = express.Router();
const conn = require('./db');
router.post('/create', function (req, res) {
connection.query('INSERT ...', function (error, results, fields) {
if (error) throw error;
// connected!
});
});
router.post('/update', function (req, res) {
connection.query('UPDATE SET ...', function (error, results, fields) {
if (error) throw error;
// connected!
});
});
AND SO ON the same goes to the other api resources that was omitted in these examples..
What is the drawback in this connection design?
Please correct me if I'm wrong. I think, even though you export the connection object, you're still managing the connection one by one.
Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources
Wikipedia
And from the same doc,
This is because two calls to pool.query() may use two different connections and run in parallel
So the best way is to use pool for managing the connections
Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.
Hope that helps.
I am trying to incorporate mongoDB into my application, however when I try to add to a collection I get the error 'cannot read property of 'insert' undefined when trying to start the server with nodeJS.
I appreciate that this has been asked before, however when I have tried to rectify the error as per another question asked on here by writing the following code, however I get var is not defined;
var accountCollection = var mongodb = mongodb.collection('account');
accountCollection.insert({username:"wendy3", password:"lilac3"});
The relevant code for my server is below, I have looked at many guides online and nothing seems to solve my problem, so any help would be appreciated.
//create server, listening on port 3000
//when there is a request to port 3000 the server is notified
//depending on the request a specific action will be carried out
var mongodb = require("mongodb");
//create connection to MongoDB
var db = mongodb('localhost:27017/Game', ['account', 'progress']);
//insert into collection
db.account.insert({username:"wendy3", password:"lilac3"});
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var colors = require('colors/safe');
Connection to a database is an asynchronous operation but you're trying to access it as if it was synchronous.
If you look at the examples for the package you're using, it shows that you must you use a callback function which gets called once the connection response is received:
var MongoClient = require('mongodb').MongoClient;
// Connection URL
var url = 'localhost:27017/Game';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if (err) return console.log('Error: ' + err);
console.log("Connected correctly to server");
});
Thank you - I think I understand now ( I am new to MongoDB so please forgive me)
I now have the following code; however I am receiving error invalid schema, expected mongodb. Have I maybe put MongoClient in place of mongodb somewhere? So I can see that it is trying to connect, however the callback is returning an error.
Code:
var MongoClient = require('mongodb').MongoClient;
//connection url
var url = ('localhost:27017/Game', 'account', 'progress');
//use connect method to connect to server
MongoClient.connect(url, function(err, db){
if (err) return console.log('Error: ' + err);
console.log('mongodb is connected to the server');
});
Using sequel pro I have created a database called test. It has one table called users. In that table there is one user -> id=1, name=Phantom.
I have installed the mysql node module
When I run the code below I get The solution is: undefined.
Can anyone advise how I can connect to database and show the users?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost:8889',
user : 'root',
password : 'root',
database : 'test'
});
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows);
});
connection.end();
It shows the following error :
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/Users/fitz035/Desktop/sony/presave/node_modules/mysql/lib/Connection.js:425:13)
I am running the db through MAMP. These are the db settings :
Host: localhost
Port: 8889
User: root
Password: root
Socket: /Applications/MAMP/tmp/mysql/mysql.sock
Node is asynchronous, so connection.end() is likely to happen before your query calls back. Also, specify the port Mysql is running on when non-standard.
try this :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'test',
port: 8889
});
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if(err) console.log(err);
console.log('The solution is: ', rows);
connection.end();
});
If it on VPS configured with Firewall, you need to whitelist your IP via SSH. Otherwise it still throws exactly above error even after adding via cPanel's RemoteMYSQl
# csf -a [RemoteIP]
# csf -r
You can do it quickly via WHM too. Just posted as it may help someone.
Check your current MySQL server port and change to:
DB_PORT=3304