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?
Related
strong textI'm trying to create my first CRUD with Mysql, Node js and Express.js following a tutorial.
The problem is, in the video this code works, but in my visual give the error aboyt getConnection is not a function.
If anyones can help, I'll apreciate.
Server.js
const express = require("express");
const mysql = require("mysql");
const myconn = require("express-myconnection");
const routes = require("./routes");
const app = express();
const serverPort = process.env.PORT || 9000;
const dbOptions = {
host: "localhost",
user: "3306",
password: "123456",
database: "catalog",
};
//server running
app.listen(serverPort, () => {
console.log(`App listening at ${serverPort}`);
});
//routes
app.get("/", (req, res) => {
res.send("welcome to my API");
});
app.use("/phones", routes);
Routes.js
const express = require("express");
const routes = express.Router();
const myconn = require("express-myconnection");
routes.get("/", (req, res) => {
req.getConnection((err, conn) => {
if (err) return res.send(err);
conn.query("SELECT * FROM phones", (err, rows) => {
if (err) return res.send(err);
res.json(rows);
});
});
});
module.exports = routes;
UPDATE : solved.
IT WAS A POINT after catalog and I didn't write the port correctly!!!!!
I am creating a simple server application using the following code
const express = require('express');
const mysql = require('mysql');
const PORT = process.env.PORT || 3000;
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'mydata',
});
connection.connect(function (err) {
err ? console.log(err) : console.log(connection);
});
require('./routes/html-routes')(app);
app.listen(PORT, () => {
console.log('app running on port %s', PORT);
});
module.exports = app;
in file server.js
and then a route in file html-routes.js
const mysql = require('mysql');
module.exports = function (app) {
app.get('/', function (req, res) {
connection.query('select * from mydata;', function (err, data) {
err ? res.send(err) : res.json({ mydata: data });
});
});
};
to get data from database
I get the error
ReferenceError: connection is not defined
at /Users/arjunbhandari/Desktop/GL-IT/backend/routes/html-routes.js:5:5
I have struggled for the past 6 hours and cannot understand the problem.
Thanks
As the error states, there is no connection defined (or inherited) within ./routes/html-routes.js.
You still can pass the connection property as a second argument to your exported function:
const mysql = require('mysql');
module.exports = function (app, connection) {
app.get('/', function (req, res) {
connection.query('select * from mydata;', function (err, data) {
err ? res.send(err) : res.json({ mydata: data });
});
});
};
then update the route mounting call within your main server file:
require('./routes/html-routes')(app, connection);
You should review your route implementation logic as this should not be the best design approach to use data-store connections.
I am building a rest api with node.js and mysql. But in my GET I am getting a error of "could not get any response" with router.get that uses the mysql.
Here is my code, mt it helps.
server.js
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
app.js
const express = require('express');
const app = express();
const userRoutes = require('./api/routes/user');
var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : ' ',
database : 'achai_db'
});
res.locals.connection.connect();
next();
});
user.js
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from users', function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
module.exports = router;
In that user.js if i use a get without using the mysql the connection works.
You need to understand JavaScript nature(Asynchronous programming) and you must not open mysql connection in each request, you can use connection pooling and keep connection open, just acquire connection and release it after query.
updated app.js
const express = require('express');
const app = express();
const userRoutes = require('./api/routes/user');
const mysql = require('mysql');
//Database connection
const pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : ' ',
database : 'achai_db'
});
app.use(function(req, res, next){
pool.getConnection(function(err, connection) {
res.locals.connection = connection;
next(err);
});
});
updated user.js
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from users', function (error, results, fields) {
res.locals.connection.release();
if (error) throw error;
//res.json({"status": 200, "error": null, "response": results});
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
module.exports = router;
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 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..