I want to perform a basic CRUD with mysql and I installed some modules like npm install mysql,npm install path, npm install routes but there is a problem which I'm facing is most middleware error here is my
app.js
var express = require('express');
var routes = require('./routes');
var http = require('http')
var path = require('path');
//load customers route
var customers = require('./routes/customers');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
// all environments
app.set('port', process.env.PORT || 80);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
port : 80, //port mysql
database:'nodejs'
},'pool') //or single
);
app.get('/', routes.index);
app.get('/customers', customers.list);
app.get('/customers/add', customers.add);
app.post('/customers/add', customers.save);
app.get('/customers/delete/:id', customers.delete_customer);
app.get('/customers/edit/:id', customers.edit);
app.post('/customers/edit/:id',customers.save_edit);
app.use(app.router);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
and here is other customer.js
exports.list = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM customer',function(err,rows)
{
if(err)
console.log("Error Selecting : %s ",err );
res.render('customers',{page_title:"Customers - Node.js",data:rows});
});
//console.log(query.sql);
});
};
exports.add = function(req, res){
res.render('add_customer',{page_title:"Add Customers - Node.js"});
};
exports.edit = function(req, res){
var id = req.params.id;
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM customer WHERE id = ?',[id],function(err,rows)
{
if(err)
console.log("Error Selecting : %s ",err );
res.render('edit_customer',{page_title:"Edit Customers - Node.js",data:rows});
});
});
};
exports.save = function(req,res){
var input = JSON.parse(JSON.stringify(req.body));
req.getConnection(function (err, connection) {
var data = {
name : input.name,
address : input.address,
email : input.email,
phone : input.phone
};
var query = connection.query("INSERT INTO customer set ? ",data, function(err, rows)
{
if (err)
console.log("Error inserting : %s ",err );
res.redirect('/customers');
});
});
};
exports.save_edit = function(req,res){
var input = JSON.parse(JSON.stringify(req.body));
var id = req.params.id;
req.getConnection(function (err, connection) {
var data = {
name : input.name,
address : input.address,
email : input.email,
phone : input.phone
};
connection.query("UPDATE customer set ? WHERE id = ? ",[data,id], function(err, rows)
{
if (err)
console.log("Error Updating : %s ",err );
res.redirect('/customers');
});
});
};
exports.delete_customer = function(req,res){
var id = req.params.id;
req.getConnection(function (err, connection) {
connection.query("DELETE FROM customer WHERE id = ? ",[id], function(err, rows)
{
if(err)
console.log("Error deleting : %s ",err );
res.redirect('/customers');
});
});
};
every time when i go to cmd and run the nodo app the error occur
Error: Most middleware (like logger) is no longer bundled with Express and must
be installed separately. Please see https://github.com/senchalabs/connect#middle
ware.
at Function.Object.defineProperty.get (C:\Users\Tahir\Desktop\node_modules\e
xpress\lib\express.js:89:13)
at Object.<anonymous> (C:\Users\Tahir\Desktop\nodecrud-master\app.js:23:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
any body help to figure out where is the issue is ??
this code depend on express 3.4.0 version... it not work on express 4.x then express 4.x upgrade some package and middleware...... logger('dev') not work... var logger=require('morgan');... i give some more idea
uninstall express4 and express-generator
like
uninstall
-------------
npm uninstall express -g
npm uninstall express-generator -g
install
---------
npm install express#3.4.0 -g
npm install express-generator -g
npm express -e appname (this is express generator)
>cd appname
appname>npm install
appname>npm install mysql
appname>npm install express-myconnection
after to replace all ur code copy and paste it
then run
appname>node app.js
all the best ........... is code really help u..
Related
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!');
});
});
Hello mates, first, I hope everyone is in good health.
Sorry if this question is a little confuse, but i'm trying creating a API/webservice that works with MySql, so I have
in root (/) the file bd.js with the connection
bd.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'skey-9'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
then i add to /app.js and have the routes of diferente directories
app.js:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const db = require('./bd');
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/order');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
//Routes
app.use('/products', productRoutes);
app.use('/orders', orderRoutes);
in the final i'm trying to query a Select in /routes/products.js
products.js:
const express = require('express');
const router = express.Router();
var db = require('./../bd');
con.connect((err) => {
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query('SELECT * FROM teste', (err,rows) => {
if(err) throw err;
console.log('Data received from Db:');
console.log(rows);
});
router.get('/', (req, res, next) => {
res.status(200).json({
message: 'handling GET requests to / products',
query: rows
});
});
module.exports = router;
but i'm getting a error i already tried to "playing" with the bd files.
the error:
C:\NODE\node-rest\server.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)
at Function.Module._load (internal/modules/cjs/loader.js:840:27)
at Module.require (internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (C:\NODE\node-rest\api\routes\products.js:3:10)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\NODE\\node-rest\\api\\routes\\products.js',
'C:\\NODE\\node-rest\\app.js',
'C:\\NODE\\node-rest\\server.js'
]
My question is how can i do a "global" mysql connection to all the app I'm creating.
soo i have 2 subpath's, and for some reason i had to change
var db = require('./../bd'); "
to
var db = require('..\\..\\bd'); "
forget this dont resolve my problem, we have to run a connection to all the router's?
I have a folder called NEsql, located in a folder called sqlnames1. Inside the NEsql folder, I have the following files.
sqlcreatedb.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE names", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
sqlcreatetable.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "names"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a table named "customers":*/
var sql = "CREATE TABLE people (id INT AUTO_INCREMENT PRIMARY KEY, firstName VARCHAR(255), lastName VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
sqlinsertvalues.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "names"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO people (firstName, lastName) VALUES ?";
var peoplenames = [
['Vedant', 'Apte'],
['Vedant', 'Savalajkar'],
['Vinay', 'Apte'],
['Varda', 'Apte'],
['Mihir', 'Wadekar'],
['Mihir', 'Kulkarni'],
['Eesha', 'Hazarika'],
['Eesha', 'Gupte'],
['Raunak', 'Sahu'],
['Hritvik', 'Agarwal'],
['Mahima', 'Kale'],
['Shivani', 'Sheth'],
['Arya', 'Chheda'],
['Diya', 'Shenoy']
];
con.query(sql, [peoplenames], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
All of these files work, as I am able to complete all the tasks and successfully receive all the corresponding console.log statements. However, I am unsure as to how I am supposed to connect these files to the app.js file located inside the sqlnames1 folder. Anyone know how to do this?
Here is my app.js file.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
What you're trying to do could simply just be the content of the app.js file you could require your package there and run these functions. However if going that route is what you choose it you could store them in a variable and then use a module.export like so
variable_name = [desired content to export]
module.export = variable_name
If you'd like to go about building a database through separate files than your app.js you should look at the package sequelize. This is more along the lines of you're trying to do.
https://www.npmjs.com/package/sequelize
Responding to your comment if you are trying to build a db upon running app.js. You are again better off looking at an ORM of some sort that will do it better than the mysql package. With it you can import the db to your app.js and simply use
require('path to db')
then using the db how you see fit, but again building your db in this way will be difficult to do as you would have to run
node filename.js
for every single one, so again if not sequelize i would strongly recommend looking at another ORM that will get this job done for you much faster and easier. As soon as you run your app.js it will build and then run, the mysql package is not the best tool to use for what it seems you are trying to do.
I have already read the post Node Mysql Cannot Enqueue a query after calling quit, the conn.end() is in my query block.
My issue is that conn.end in my dashboard.js does not work and breaks the app with the following error.
I need to use it because MySQL connections are flooding the system till Database stop accepting more of them since they all stay open each time that are used.
For this post I will use only one (dashboard.js) of the several routes of my NodeJS application.
`Event.js` is not a part of my working files, probably is a file from `./node_modules`
|events.js:183
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Quit after invoking quit.
at Protocol._validateEnqueue (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\Protocol.js:204:16)
at Protocol._enqueue (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\Protocol.js:139:13)
at Protocol.quit (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\Protocol.js:92:23)
at Connection.end (E:\NodeJS\Project-Change\node_modules\mysql\lib\Connection.js:249:18)
at ServerResponse.res.end (E:\NodeJS\Project-Change\node_modules\express-myconnection\lib\express-myconnection.js:114:54)
at ServerResponse.send (E:\NodeJS\Project-Change\node_modules\express\lib\response.js:191:8)
at fn (E:\NodeJS\Project-Change\node_modules\express\lib\response.js:896:10)
at View.exports.renderFile [as engine] (E:\NodeJS\Project-Change\node_modules\ejs\lib\ejs.js:323:3)
at View.render (E:\NodeJS\Project-Change\node_modules\express\lib\view.js:76:8)
at Function.app.render (E:\NodeJS\Project-Change\node_modules\express\lib\application.js:527:10)
at ServerResponse.res.render (E:\NodeJS\Project-Change\node_modules\express\lib\response.js:900:7)
at Query._callback (E:\NodeJS\Project-Change\routes\dashboard.js:39:17)
at Query.Sequence.end (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
at Query._handleFinalResultPacket (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
at Query.EofPacket (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\sequences\Query.js:123:8)
at Protocol._parsePacket (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\Protocol.js:279:23)
app.js (only relative lines)
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
app = express(),
expressValidator = require('express-validator'),
session = require('express-session'),
passport = require('passport'),
flash = require('connect-flash'),
passportConfig = require('./config/passport'),
dbConfig = require('./config/db');
// skipping code about static files, bodyparser, expressValidator, session, passport
passportConfig(passport)
/*MySQL connection*/
var connection = require('express-myconnection'),
mysql = require('mysql');
app.use(
connection(mysql, dbConfig,'request')
);
var dashboard = require('./routes/dashboard.js'); // in this route I apply conn.end()
var router = require('./routes/rates.js');
// skipping app.post/app.get code for /login & /logout & isLoggedIn middleware
app.use('/', router);
app.use('/', dashboard); // issue on that
app.get('/',function(req,res){
res.render('./dashboard.ejs'); //issue on that
});
module.exports = app;
routes/dashboard.js (route)
var express = require('express');
var router = express.Router();
var dashboard = express.Router();
dashboard.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
var dashboard = router.route('/');
//show the CRUD interface | GET
dashboard.get(function(req,res,next){
req.getConnection(function(err,conn){
if (err) return next("Cannot Connect");
var query = conn.query('SELECT SUM(total_price) AS transactions_total FROM transactions WHERE date_created = CURDATE(); SELECT SUM(total_profit) AS total_profit FROM transactions', function(err,rows){
if(err){
console.log(err);
return next("MySQL error, check your query");
}
var ab = {data:rows[0]};
var total_profit = {data:rows[1]};
res.render('dashboard',{ab, total_profit});
conn.end(); // causes the described error
});
// conn.end(); even tried here
});
});
dashboard.all(function(req,res,next){
console.log("route for dashboard executed");
console.log(req.params);
next();
});
module.exports = router;
console.log('dashboard.js loaded!');
config/db.js
module.exports = {
host : 'localhost',
user : 'root',
password : '',
database : 'mydb',
multipleStatements: true,
debug : false
}
config/passport.js
External presentation in case is needed here
I tried to push my project to heroku and connect jawsdb with the application. I input jawsdb info into my server.js and updated it then pushed to heroku. But I'm getting this erorr and the application wont load. I think it has something to do with the way I'm setting up the database.
I am receiving the following "Access denied for user" error:
https://ibb.co/giRO5m
this is my code: server.js
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var logger = require('morgan');
var request = require('request');
var cheerio = require('cheerio');
var methodOverride = require('method-override')
var fs = require("fs");
var hbs = require('hbs');
// Set up Express
var app = express();
var router = express.Router();
//handlebars
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
// override with POST having ?_method=DELETE
app.use(methodOverride('_method'))
// Set up Mysql
var con = mysql.createConnection({
host: "t89yihg12rw77y6f.cbetxkdyhwsb.us-east-1.rds.amazonaws.com",
port: 3306,
user: "swvr0i1j9ny720mk",
password: "e3lzkqag4dmeqhup"
});
//conecting to mysql
con.connect(function(err) {
if (err) throw err;
console.log("Database connected to the matrix..");
});
con.query('CREATE DATABASE IF NOT EXISTS warehouse', function (err) {
if (err) throw err;
con.query('USE warehouse', function (err) {
if (err) throw err;
con.query('CREATE TABLE IF NOT EXISTS storage('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'link VARCHAR(255),'
+ 'item VARCHAR(255),'
+ 'stock VARCHAR(255)'
+ ')', function (err) {
if (err) throw err;
});
});
});
// Parse application/x-www-form-urlencoded
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Serve static content for the app from the "public" directory in the application directory.
app.use(express.static(__dirname + '/public'));
//prints database to page
app.get('/index', function(req,res) {
con.query('SELECT * FROM storage;', function(err, data) {
if (err) throw err;
//test it
//console.log('The solution is: ', data);
//test it
//res.send(data);
res.render('index', {storage : data});
});
});
//delete data entry
app.delete('/delete', function(req,res){
con.query('DELETE FROM storage WHERE id = ?', [req.body.id], function(err, result) {
if (err) throw err;
res.redirect('/index');
});
});
// Open Server
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
JawsDB does not let you choose the database name or create a new database name. Instead, you will need to connect via a workbench tool and see what the database name they have given you is (for example, the below show my database name JawsDB assigned).
Then, use this database in your code instead of the one you named "warehouse." For example, if I were to do this with the schema JawsDB named for me, I would use 'jdjkhrjps1cgj89h'
con.query('USE jdjkhrjps1cgj89h', function (err) {
if (err) throw err;
con.query('CREATE TABLE IF NOT EXISTS storage('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'link VARCHAR(255),'
+ 'item VARCHAR(255),'
+ 'stock VARCHAR(255)'
+ ')', function (err) {
if (err) throw err;
});
});