So im pulling my hair here and everything I've tried hasn't worked. I have a simple node.js app structure, like this:
var express = require('express');
var path = require('path');
var mysql = require('mysql');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
//Database handler
//Here is completed with the data
var con = mysql.createConnection({
host: "",
user: "",
password: "",
database: ""
});
con.connect(function (err) {
if(err) throw err;
console.log("connected");
});
app.listen(55132, function () {
console.log("Server running at port 55132");
});
module.exports = app;
Quite simple, some routing but nothing weird. I need to use the variable con in my other scripts, so i've tried this:
module.exports.database = con;
So i should be able to use it in my index.js script (see var indexRouter), soooo here is the index.js script:
var express = require('express');
var router = express.Router();
let app = require('../app');
let connection = app.database;
console.log(app); //Here returns {} so I canĀ“t access any of the properties of the module
/* GET home page. */
router.get('/', function(req, res, next) {
}
module.exports = router;
I don't know what should I do, some suggestion?
for forther reading i recommend you to read this
https://nodejs.org/api/modules.html#modules_exports_shortcut
just change you app file export to
module.exports = {app,con};
and in your index file
const {app,con} = require('./app');
let connection = con;
You can you try with
for and example :
var function = function(coid, userid, callback) {}
exports.function = function ;
in your case
exports.database = con;
Now it should work, you won't need to add module in the above.
Related
So I created a new node.js project and used express.js to build the basics to start of. Now I want to do a simple get call to get data from my database through a connection pool. When I do the call in app.js there is no problem, but when trying to do the same call from my users.js file in a get route it throws 'connection pool Cannot read properties of undefined (reading 'getConnection')'.
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// establish connection to database
var conpool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: '****',
password: '****',
database: 'db_name'
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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, conpool};
user.js (located in routes directory which is on the same hierarchy level as app.js)
var express = require('express');
var router = express.Router();
var db = require('../app').conpool;
/* GET users listing. */
router.get('/get', function (req, res, next) {
db.getConnection((err, connection) => {
if (err) throw err;
var sql = null;
if (req.query.name) {
sql = 'SELECT * FROM users WHERE name = ' + sql.escape(req.query.name);
} else {
sql = 'SELECT * FROM users';
}
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
});
module.exports = router;
Does anyone have any idea why this is happening? Is there something wrong with how I am using module.exports? Is it a problem of trying to call a function on a reference instead of the original pool object?
It seems Evert's solution was the one I was looking for. I'll describe the changes I made compared to the files shown in my question to show how it solved it.
I made a completely new file database.js (on the same level of hierarchy as app.js):
var mysql = require('mysql');
var conpool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: '****',
password: '****',
database: 'db_name'
});
module.exports = conpool;
and deleted all these lines of code from app.js
in user.js only one line changed:
var db = require('../app.js')
to
var db = require('../database');
I have a probleme to deploy my web site with node on a renote host
the first script server.js displays the server connexion
But my midelware mw.js seems to not work
Nothing is display
No error message in the logs
Maybe a trouble to display ma index.ejs?
Thanks for your help
My node app works fine in local
my Main files server.js
/**
* Module dependencies.
*/
var express = require('express')
var middelware = require('./routes/mw')
var http = require('http')
var path = require('path');
//var methodOverride = require('method-override');
var mysql = require('mysql');
var bodyParser=require("body-parser");
var app = express();
var cookieParser = require("cookie-parser");
//console.log(session);
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public/css')));
app.use(express.static(path.join(__dirname, 'public/javascript')));
app.use(express.static(path.join(__dirname, 'public/image')));
app.use('/',middelware );
app.listen(3000)
console.log('3000 is the magic port');
mw.js
var express = require('express');
var url = require('url');
var router = express.Router();
var path = require('path');
var http = require('http');
var mysql = require('mysql');
/* GET pages listing. */
router.get('/:nom/', function(req, res, next) {
let pages=['accueil','article','contact'];
var bool=false;
pages.forEach(function(nomPage) {
if(nomPage==req.params.nom){
bool=true;
console.log(nomPage);
nomP=req.params.nom;
// requete mysql
var con = mysql.createConnection({
host: "localhost",
port:3306,
user: "root",
password: "",
database: "pageWeb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
// Select where
con.query("SELECT * FROM pages WHERE nomP = '"+nomP+"'", function (err, result) {
if (err) throw err;
ctnpage=result[0].contenuP;
console.log(ctnpage);
// affichage via ejs dans la page
res.render('index', {
contenuP:ctnpage ,
nomP:pages
});
});
});
What can I do?
Thanks for your help
Hi i have setup three project api(nodejs) , admin(angular 4) and website(angular 4) , after build i got two UI folder admin-dist and web-dist , I want to access these app based on URL '/admin' will access admin-dist and '/' will access web-dist , I have placed these two folder on of api folder
For accessing these app i have written node code like this ,But i am not able to access ,
Please help me, Thanks in advance ..
app.js
var express = require('express');
router = express.Router();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cookieParser = require('cookie-parser');
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var cors = require('cors');
var User = require('./models/user.model');
var dbConfig = require('./config/db');
var app = express();
app.use(cors());
app.use(cookieParser());
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, function (err) {
if (err) {
console.log('faild to connect with mongo DB', err);
}
else {
console.log('Connection open with mongo db');
}
})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
var userRoute = require('./routes/user.route')(router);
// var profileRoute = require('./routes/profile.route')(app);
// var productRoute=require('./routes/products.route')(app);
app.use(express.static(__dirname + '/admin-dist'));
app.get('/admin', function (req, res) {
console.log('admin route');
return res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.get('/admin/*', function (req, res) {
res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.use(express.static(__dirname + '/front-dist'));
app.get('/', function (req, res) {
console.log('web route');
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.use('/*',function(req, res) {
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.listen(port, function (err) {
if (err) {
console.log(err);
}
else {
console.log('Server api runing on port ', port);
}
})
I am trying to run a query in a view (.ejs file). However, since the keyword require is not defined in a .ejs file, I need to export it from my main file, server.js.
The whole code for my server.js file is below and this is the specific snippet with which I need help.
app.engine('html', require('ejs').renderFile);
exports.profile = function(req, res) {
res.render('profile', { mysql: mysql });
}
I need to be able to use the mysql.createConnection in my profile.ejs file.
Any help would be great.
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
var Connection = require('tedious').Connection;
var config = {
userName: 'DESKTOP-S6CM9A9\\Yash',
password: '',
server: 'DESKTOP-S6CM9A9\\SQLEXPRESS',
};
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "yashm"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql="Select * from test.productlist";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
app.engine('html', require('ejs').renderFile);
exports.profile = function(req, res) {
res.render('profile', { mysql: mysql });
}
//--------------------------------------------------------------------------------
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'test run' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
Like already said in the comment, you have to do your query logic in your server.js and then pass the data to your view (or maybe even pre-process it!)
exports.profile = function(req, res) {
con.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
res.render('profile', { data: results });
});
}
In your ejs you can loop trough the data, and acces the fields as data[i]['fieldname']
<ul>
<% for(var i=0; i<data.length; i++) {%>
<li><%= data[i]['id'] %></li>
<% } %>
</ul>
I am pretty new with node.js and express so bear with me please.
I am wondering how i can get a mysql instance and use it in my controller. I have 4 files that look like this:
see my comment in the controller.js file
server.js :
var express = require('./config/express');
var app = express();
module.exports = app;
app.listen(3000);
console.log('server running');
express.js :
var express = require('express'),
bodyParser = require('body-parser'),
mysql = require('mysql');
module.exports = function() {
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.set('views','./app/views');
app.set('view engine','ejs');
//NOT SURE WHAT TO DO HERE OR WHERE TO PUT THE CONNECTION DETAILS
var dbConnection = mysql.createConnection({
host : 'localhost',
user : 'someuser',
database : 'somedb',
password : 'somepass'
});
//connection.connect();
//
//connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
// if (err) throw err;
// console.log('The solution is: ', rows[0].solution);
//});
//
//connection.end();
require('../app/routes/index.server.routes.js')(app);
app.use(express.static('./public'));
return app;
};
routes.js :
module.exports = function(app) {
var index = require('../controllers/index.server.controller');
app.get('/', index.render);
app.post('/', index.stuff);
};
controller.js :
exports.render = function(req, res) {
//DO DB STUFF HERE
res.render('index', {
title: 'this is the title'
});
};
exports.stuff = function(req, res) {
res.render('index', {
title: 'this is the title post'
});
};
To use the connection instance in your controller, you'll need to pass it from the express.js file to the controller.js file. The first step is to pass the connection instance to the router:
express.js
require('../app/routes/index.server.routes.js')(app, connection);
This will make it available in the routes.js file. You then need to pass the same connection instance to the controller.
index.server.routes.js
module.exports = function(app, connection) {
var index = require('../controllers/index.server.controller')(connection);
app.get('/', index.render);
app.post('/', index.stuff);
};
The controller will need to be refactored so it takes a connection instance as an argument:
index.server.controller.js
function IndexController(connection) {
controllerMethods = {};
controllerMethods.render = function (req, res) {
// You can use the connection instance here.
connection.connect()
// Run your query
connection.end()
...
};
// Define other methods for the controller
// Return the object that holds the methods.
return controllerMethods;
}
module.exports = IndexController;