Connection to Database and Create a database in Node - mysql

I've tried to implement this code and terminal throws error something like this stucked in it As I've applied this code but it throws the error
"Access denied for user ''#'localhost' to database 'mydb'"
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "myusername",
password: "mypassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});

create a config folder and create a file databaseConfig.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection =mysql.createConnection(config); //added the line
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
module.exports ={
connection : mysql.createConnection(config)
}
create a app.js file
var express = require('express');
var cors = require('cors');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
create a controller.js file
var config = require('../../databaseConfig.js');
var connection= config.connection
connection.query ('CREATE DATABASE mydb', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});

Related

Express taking forever to load mySQL query?

I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.

Error in delete DB record using Node.JS and MYSQL

I'm performing CRUD operations using MYSQL and NodeJS express. Their error in deleting a record from DB, I don't know why I was getting a problem as i have copied the delete query from SQL where it is working properly. Here it is 'DELETE FROM tblltest WHERE id=?'. I manually add 'id' like 'DELETE FROM tblltest WHERE id=2' then it will delete the record from DB. Please help me out to solve this issue. Here are my lines of code.
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sampledb'
});
app.delete('/:id' , function(req , resp) {
connection.query('DELETE FROM `tblltest` WHERE `id`=?' , function(error , rows , fields){
if(!error){
console.log('Successful deleted!! \n');
resp.json(rows);
}else{
console.log('Error in deleting');
}
});
})
app.listen(1337);
You need to access the id route parameter in your delete API Node method, and then also bind this id value to the delete query:
app.delete('/:id', function(req, resp) {
var id = req.params.id;
connection.query('DELETE FROM tblltest WHERE id = ?', [id],
function(error, rows, fields) {
if (!error) {
console.log('Successful deleted!! \n');
resp.json(rows);
}
else {
console.log('Error in deleting');
}
});
})
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
//start mysql connection
var connection = mysql.createConnection({
host : 'localhost', //mysql database host name
user : 'root', //mysql database user name
password : '', //mysql database password
database : 'sampledb' //mysql database name
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
//end mysql connection
//start body-parser configuration
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//end body-parser configuration
//create app server
var server = app.listen(1337, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
//rest api to delete record from mysql database
app.delete('/employees', function (req, res) {
console.log(req.body);
connection.query('DELETE FROM `tblltest` WHERE `id`=?', [req.body.id], function (error, results, fields) {
if (error) throw error;
res.end('Record has been deleted!');
});
});

Connection_refused when trying to use MySQL and node.js. When using cmd it does work

I created a server.js file which looks like this.
var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port);
console.log('todo list RESTful API server started on: ' + port)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "**",
password: "**",
database: "test"
});
app.get('/nodeapi/getimg',function(req,res){
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM images", function (err, result, fields) {
if (err) throw err;
console.log(result[1].image);;
});
})})
When I run this file in my command terminal I get the correct result.
When I create a http.get function like this for my ionic app:
getimg(){
var url = 'http://localhost:3000/nodeapi/getimg';
this.http.get(url).subscribe(responseData => console.log(responseData));}
I get an error saying net::ERR_CONNECTION_REFUSED. I have looked everywhere but cannot seem to find it. I am using phpmyadmin for the database. Would anyone please be so kind to explain to me what I am doing wrong.
Give this example a try. Also, do you expect more than one result from your query? If not you will want to use result[0] not 1 to get the first (and maybe only) result (located at index 0).
var express = require('express');
var cors = require('cors');
var mysql = require('mysql');
var port = process.env.PORT || 3000;
var app = express();
app.use(cors());
app.options('*', cors());
var con = mysql.createConnection({
host: "localhost",
user: "**",
password: "**",
database: "test"
});
app.get('/nodeapi/getimg', function(req, res) {
con.connect(function(err) {
if(err) throw err;
con.query("SELECT * FROM images", function(err, result, fields) {
if(err) throw err;
console.log(result[1].image);
res.send(result[1].image); // send the value back to the caller.
});
})
})
app.listen(port, function() {
console.log('CORS-enabled web server listening on port 80')
})

Node.js : Access denied for user 'root'#'localhost' (using password: NO)

I'm having problems in connecting my node.js application with mysql database. I have gotten the error below:
Access denied for user 'root'#'localhost' (using password: NO)
I did a little digging and found these test for connection:
First code:
mysql -u root -p -h 127.0.0.1 -P 3306
I tested the above code and it will prompt out the password and gave me the access to it.
Second code:
mysql -u root -p -h > localhost -P 3306
I tested the above code and gotten an access is denied
From my understanding, correct me if I'm wrong, localhost == 127.0.0.1. So what is the reason for one of them not having access since they are the same?
Please help me. I've been stuck on this for hours. Thank you for your time.
My node.js code for login (not finished):
module.exports = function(app,passport){
let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '9#v62STH9J',
database: 'fyp',
port: 3306
});
connection.connect(function(err){
if(err){
return console.log('error: ' + err.message);
}
console.log("connected.");
});
app.get('/login', function(req,res){
res.render('loginpage', {message:req.flash('loginMessage')});
})
app.post('/login', function(req,res){
connection.query("SELECT * FROM user", function (err, result, field){
if (err){
return console.log('error: ' + err.message);
}
Object.keys(result).forEach(function(key){
row = result[key];
if(row.u_username == req.body.username){
if(row.u_password == req.body.password){
console.log("in");
res.redirect('/' + row.u_id +'/home');
}
// else{
// // res.send('wrong');
// console.log("here");
// res.render('loginpage', {result: 'Incorrect password is entered.'});
// }
}
// else{
// console.log("here2");
// // console.log(typeof req.next);
// res.render('loginpage', {result: "Username is not found in the database."});
// }
});
});
});
app.get('/logout', function(req,res){
req.logout();
res.redirect('/login');
})
};
the main node.js:
var express = require('express');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var session = require('express-session'),
morgan = require('morgan'),
sequelize = require('sequelize'),
passport = require('passport'),
jwt = require('jsonwebtoken');
util = require('util');
mysql = require('mysql');
cookieParser = require('cookie-parser');
var app = express();
require('./controllers/user')(passport);
var compController = require('./controllers/compController');
var patController = require('./controllers/patController');
var taskController = require('./controllers/taskController');
var loginController = require('./controllers/loginController');
var staffController = require('./controllers/staffController');
var checkController = require('./controllers/checkController');
var repController = require('./controllers/repController');
var homeController = require('./controllers/homeController');
var noticeController = require('./controllers/noticeController');
app.set('view engine', 'ejs');
app.use('/assets', express.static('assets'));
app.use('/js', express.static('js'));
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended:true }));
app.use(bodyParser.json());
app.use(session({ cookie: { maxAge: 60000 }, secret: 'sarah', resave: true, saveUninitialized: true}))
app.use(flash());
app.use(morgan('dev'));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
// require('./controllers/loginController')(app,passport);
compController(app);
patController(app);
taskController(app);
staffController(app);
checkController(app);
repController(app);
homeController(app);
loginController(app);
noticeController(app);
// app.use((req,res,next) => {
// var err = new Error('Page not found');
// err.status = 404;
// next(err);
// });
// app.use((err,req,res,next) => {
// res.status(err.status || 500);
// res.send(err.message);
// })
app.listen(3003, 'localhost', function(){
console.log("Working");
});

TypeError: Cannot read property 'query' of undefined?

I am trying to deploy my node app with Docker.Here is my node app:
var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');
var mongoose =require('mongoose');
app.use(express.static("./app"));
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'node_db'
});
app.set('port',8080);
app.set('views',path.join(__dirname,'views'));
app.set('view engine','jade');
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyparser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
res.sendfile('app/index.html');
});
app.get('/getAllBlogs', function (req, res) {
pool.getConnection(function (err, connection) {
var sql = mysql.format("select * from blogs");
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
res.send(error);
}
res.send(results);
});
});
});
app.get('/getBlog/:id', function(req,res){
console.log(req.params.id);
pool.getConnection(function (err, connection) {
var sql = mysql.format("select * from blogs where id=?", [req.params.id]);
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
res.status(200).send(error);
}
res.send(results[0])
});
});
});
app.listen(app.get('port'));
console.log('~~Server Runnign on port localhost:'+app.get('port')+'~~');
Here is my Docker file:
FROM node:boron
# Create app directory
RUN mkdir -p /home/sameera/Desktop/test/app
WORKDIR /home/sameera/Desktop/test/app
# Install app dependencies
COPY package.json /home/sameera/Desktop/test/app
RUN npm install
# Bundle app source
COPY . /home/sameera/Desktop/test/app
EXPOSE 8080
CMD [ "npm", "start" ]
The docker file built successfully and when i run below command it is running properly.
docker run -p 49160:8080 img
But when i try to load a page with data that is using mysql it is
giving an error:
connection.query(sql, function (error, results, fields) {
^
TypeError: Cannot read property 'query' of undefined
}
I guess the problem is with that i can't connect to mysql with this container since i am not install or use any mysql related commands in docker file.When i remove all my sql connection and related code it is not giving any error and running properly.I am using ubuntu 14.04
You can use below code if pool is not required:
var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
app.use(express.static("./app"));
var pool = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'node_db'
});
pool.connect();
app.set('port', 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyparser.urlencoded({ extended: false }));
app.get('/test', function (req, res) {
var sql = mysql.format("SELECT * FROM users");
pool.query(sql, function (error, results, fields) {
if (error) {
res.send(error);
}
res.send(results);
pool.end();
});
});
app.listen(app.get('port'));
console.log('Server Runnign on port localhost:' + app.get('port'));
Result will be something like that:
[
{
"id": 1,
"firstName": "shubham",
"lastName": "verma",
"userName": "shubham",
"email": "shubham#email.com",
"password": "25d55ad283aa400af464c76d713c07ad",
"sessionId": "bdfb43ae-ee9e-4819-b35a-3cb254885023",
"isLive": 1,
"date": "2017-05-06T06:05:24.000Z"
}
]
But if the pool is necessary and you want to use pool then you should try below code:
var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
app.use(express.static("./app"));
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'root',
database: 'node_db'
});
app.set('port', 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyparser.urlencoded({ extended: false }));
app.get('/test', function (req, res) {
pool.getConnection(function (err, connection) {
var sql = mysql.format("SELECT * FROM users");
connection.query(sql, function (error, results, fields) {
if (error) {
res.send(error);
}
res.send(results);
connection.release();
});
});
});
app.listen(app.get('port'));
console.log('Server Runnign on port localhost:' + app.get('port'));
Result wll be like that:
[
{
"id": 1,
"firstName": "shubham",
"lastName": "verma",
"userName": "shubham",
"email": "shubham#email.com",
"password": "25d55ad283aa400af464c76d713c07ad",
"sessionId": "bdfb43ae-ee9e-4819-b35a-3cb254885023",
"isLive": 1,
"date": "2017-05-06T06:05:24.000Z"
}
]
You are using pooling to connect to MySQL and querying with connection.
Use pool for querying:
var mysql = require('mysql');
var pool = mysql.createPool({ connectionLimit : 10, host : 'example.org', user : 'bob', password : 'secret', database : 'my_db' });
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); });