Good day.
I'm trying to write a small application on Node.JS. Its meaning is simple: when the browser requests the page to access the database, get the name of the requested page and pass the data on to the user.
I work with express and mysql.
I get the data from the database, I can display the page too. The problem is that the page is given before the data comes from the database.
My code is:
var config = require('../config.json'); var mysql = require('mysql'); var connection = mysql.createConnection(config.db); connection.connect(); var getPageData = function (req, next) { req.pageData = { title: 'MySite - ' }; var sql = 'SELECT `name` FROM `pages` WHERE `path`="' + req.url + '";'; var query = connection.query(sql); query.on('error', function (err) { throw err; }); query.on('result', function(res) { req.pageData.title += res['name']; }); next(); }; router.get('/', getPageData, function (req, res, next) { res.render('index', req.pageData); }); UPD: I understood what callback is and did it through it:
function getPageData(req, callback) { var sql = 'SELECT `name` FROM `pages` WHERE `path`="' + req.url + '";'; var query = connection.query(sql); query.on('error', function (error) { throw error; }); query.on('result', function (result) { req.pageData = { title: 'MySite - ' + result['name'] }; }); query.on('end', function () { callback(req); }); } router.get('/', function (req, res, next) { getPageData(req, function () { res.render('index', req.pageData); }); }); This method works, but I suppose that there will be problems when I start before sending the page to the user to take some more data from the database. Callback hell will start. How to get out?
next();query.on('result', function(res) {...}, then aTypeError: next is not a functionerrorTypeError: next is not a function. - V2Zag