So I'm entirely new to NodeJS and wanting to eventually replace PHP with Node for my personal use.
I currently have a custom-made module where I query a database table for the page that the user is trying to get, then pull back the template file for that page.
I have the query working, and it pulls through everything fine when logging out the attr var. Ideally wanting it so when I call page.attr.title it'll pull back the result[0].title if that's possible? But just not entirely sure how I'd go about doing that.
Any help / guidance would be much appreciated - below is my pageHandlder module which I'm importing into app.js to control which view and route is being used. dbHandler just contains the database connection details along with a sanity check to ensure the connection is established.
/**
* Created by PhpStorm.
* User: Josh
* Date: 26/05/2017
* Time: 19:18
*/
var express = require('express');
var app = express();
var db = require("./dbHandler");
var url = require('url');
// On load, get the page the user wants to access
var page = app.use(function (req, resp) {
db.getConnection(function (err, tempConnection) {
if (!!err) {
tempConnection.release();
console.log('Error');
} else {
console.log('Querying database for page to serve');
tempConnection.query({
sql: 'SELECT * FROM `pages` WHERE page_url = ?',
values: [url.parse(req.url).pathname]
}, function (err, results, fields) {
tempConnection.release();
if (!!err) {
console.log('ERROR: ' + err.code)
} else {
if (results.length > 0) {
resp.json(results.length + ' Rows has been found');
console.log('Page template has been found: ' + results[0].template);
var attr = {
id: results[0].id,
title: results[0].title,
url: results[0].page_url,
template: results[0].template,
metaTitle: results[0].meta_title,
metaDescription: results[0].meta_description,
metaKeywords: results[0].meta_keywords,
position: results[0].position
};
} else {
resp.send(404);
}
}
});
}
});
});
module.exports = page;
via Josh Scott
No comments:
Post a Comment