I've start using NodeJS about a month ago. Since i don't have that much experience running code doesn't always go as want to. In some way i'm not able to connect to my PostgreSQL with node's pg package. (Good to know it works when i connect through PDO in PHP)
I have made this (simple) route/controller
var pg = require('pg');
var config = require('../config');
module.exports = function(app) {
app.get('/db-get-formules', function(req, res) {
var results = [];
var pgClient = new pg.Client(config.getDbConnectionString());
pgClient.connect();
pgClient.query('SELECT * FROM formules ORDER BY formule_id');
pgClient.on('row', function(row) {
results.push(row);
})
pgClient.on('end', function() {
done();
console.log(results);
res.json(results);
})
});
};
this is my index.js file in the config:
var configValues = require('./config');
module.exports = {
getDbConnectionString: function() {
return 'postgres://' + configValues.uname + ':' + configValues.password + '#' + configValues.host + ':' + configValues.port + '/' + configValues.database;
}
}
In that same config folder i have a config.json file that contains all of the parameters to connect
{
"uname": "username",
"database": "myDb",
"host": "localhost",
"password": "P#ssw0rd",
"port": "5432",
"idleTimeoutMillis": "30000"
}
If i run this /db-get-formules page the page keeps loading (spinning) and nothing really happens. What am i doing wrong?
Oh and just to provide you with my complete code, i have a server.js file in the root
var express = require('express');
var app = express();
var queryFormules = require('./controllers/queryFormules');
var port = process.env.PORT || 3000;
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/server', express.static(__dirname + '/public/server'));
queryFormules(app);
// application -------------------------------------------------------------
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
app.listen(port);
I don't see any other answers, and i'm not sure if this will help, but here is how I got it to work:
config.js
var pg = require('pg');
exports.conString = "pg://user:password#db_address:5432/db_name";
helper.js
var pg = require("pg");
var config = require('../config/config');
exports.runQuery= function(query, next) {
pg.connect(config.conString, function(err, client) {
if (err) {
var e = {
error: true,
message: "Unable to connect to database",
err: err,
};
return next(e);
}
client.query(query, function(err, result) {
//deal with the result
client.end();
return next(some_data_or_value);
});
});
}
Then you can call runQuery from anywhere, ofcourse you'll need to deal with the results / possible errors in the function as well.
some other file or function
var helpers = require('../services/helpers');
var query = "SELECT * FROM formules ORDER BY formule_id"
helpers.runQuery(query, function(result) {
//deal with results
});
Related
I have this procedure xyz_users_list and it return list of users with exec xyz_users_list but how do i use it in nodejs app?
Code
index.js
'use strict';
const express = require('express');
const app = express();
const mysql = require('mysql');
var connection = require('express-myconnection');
require('dotenv').config();
app.use(
connection(mysql, {
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
}, 'request')
);
app.get('/', (req, res) => {
return res.sendFile(__dirname + '/index.html');
});
//all users
var Users = require('./routes/Users');
app.get('/users', Users.list);
Users.js
'use strict';
var response = require('../res');
const { exec } = require('child_process');
exports.list = function(req, res) {
req.getConnection(function(err, connection) {
connection.query(exec('xyz_users_list'), function(err, rows) {
if (err)
console.log("%s ", err);
response.success(rows, res);
});
});
};
this code returns:
TypeError: Cannot read property 'query' of undefined
If I use code below it works just fine but since i want to use exec it's returning error.
exports.list = function(req, res) {
req.getConnection(function(err, connection) {
connection.query('SELECT * FROM `users`', function(err, rows) {
if (err)
console.log("%s ", err);
response.success(rows, res);
});
});
};
any idea?
Update
here is result of my exec xyz_users_list in SQLQuery
Your connection is coming as undefined so it is showing this error. Try this version
const sql = require("mssql");
exports.list = async function(req, res) {
const connection = await sql.connect("connectionString");
const results = await connection.request().execute("xyz_users_list");
}
Need to add the corresponding return statements but you will get an idea.
I have two files in my angular project: server.js and db_connection.js. I'm hosting the project on Heroku.
The server.js currently runs because, in my package.json, I have "start": "node server.js"
I want to connect to the database as well, but I want to put that in a separate file called db_connection.js. How should I go about making sure the code in that file runs? Do I call it from server.js? If so, how so?
My files:
server.js:
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(__dirname + '/dist/my-app'));
app.listen(process.env.PORT || 8080);
// PathLocationStrategy
app.get('*', function (req, res) {
res.sendFile('dist/my-app/index.html' , { root : __dirname});
});
console.log('Console Listening')
db_connection.js:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "my_server.net",
user: "my_username",
password: "my_password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
You could do something like this.
server.js
const express = require('express');
const app = express();
const path = require('path');
const db = require('./db_connection')
app.use(express.static(__dirname + '/dist/my-app'));
app.listen(process.env.PORT || 8080);
// PathLocationStrategy
app.get('*', function (req, res) {
res.sendFile('dist/my-app/index.html' , { root : __dirname});
});
app.get('/getSomethingFromDB', db.getSomethingFromDB)
app.post('/postSomethingToDB', db.postSomethingToDB)
console.log('Console Listening')
db_connection.js
const mysql = require('mysql')
const con = mysql.createConnection({
host: "my_server.net",
user: "my_username",
password: "my_password",
database: 'my_db_name'
});
con.connect( err => {
if (err) throw err;
console.log("Connected")
});
module.exports = {
getSomethingFromDB: (req, res) => {
const getQuery = `SELECT * FROM some_table WHERE condition`
con.query(getQuery, (error, results, fields) => {
if (error) {
return res.status(500).send("DB Error")
} else {
return res.status(200).send(results)
}
})
},
postSomethingToDB: (req , res) => {
// Your code for post requests
},
// Similarly other functions
}
I have created a API for different webpages with some CRUD functionality for POST, GET, etc. methods using Node.js, express and mongoose. I also have a big app.js file, where my routing logic and functions for CRUD methods reside.
So in the app.js file, I have to do the CRUD functionality and routing logic for every model in my models folder. This is quite much for on file, how can I separate the CRUD logic for my models, and the routing logic? So that it still works as normal without hosing my file?
I was thinking to separate the CRUD into a "controllers" folder and the routing into the "routes" folder, but I dont know how exactly, and what to require at what place..
My app.js looks like:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var morgan = require("morgan");
var routes = require('./routes');
var cors = require('cors')
//configure app
app.use(morgan('dev')); //log requests to the console
//configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 5000;
//DATABASE SETUP
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/DNZ'); //connect to uor datbaase
//Handle the connection event, get reference to database.
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("DB connection alive");
});
//DNZ models live here
var FA = require('./models/DNZmodels/FA');
var FP = require('./models/DNZmodels/FP');
//ROUTES FOR OUR API
//=============================================================================
//create our router
var router = express.Router();
//middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
console.log('Today is:', Date())
next();
});
//test route to make sure everything is working (accessed at GET http://localhost:5000/DNZ/)
router.get('/', function(req, res) {
res.json({ message: 'Welcome to DNZ API!' });
});
//on routes that end in /FA
//----------------------------------------------------
router.route('/FA')
// create a FA (accessed at POST http://localhost:8080/DNZ/FA)
.post(function(req, res) {
//console.log(req.body);
//console.log(req.body.params);
//res.setHeader('Content-Type', 'application/json')
//res.send(JSON.stringify(req.body));
/*
var timestamp = req.body.Timestamp;
var prognostizierterBetriebswert = req.body.PrognostizierterBetriebswert;
var posFlexPot = req.body.posFlexPot;
var negFlexPot = req.body.negFlexPot;
var leistungsuntergrenze = req.body.Leistungsuntergrenze;
var leistungsobergrenze = req.body.Leistungsobergrenze;
var posGesEnergie = req.body.posGesEnergie;
var negGesEnergie = req.body.negGesEnergie;
var preissignal = req.body.Preissignal;
var dummy1 = req.body.Dummy1;
var dummy2 = req.body.Dummy2;
var dummy3 = req.body.Dummy3;
var fa = new FA({
Timestamp: timestamp,
Leistungsuntergrenze: leistungsuntergrenze,
Leistungsobergrenze:leistungsobergrenze,
PrognostizierterBetriebswert :prognostizierterBetriebswert,
posFlexPot: posFlexPot,
negFlexPot:negFlexPot,
posGesEnergie: posGesEnergie,
negGesEnergie: negGesEnergie,
Preissignal:preissignal,
Dummy1: dummy1,
Dummy2: dummy2,
Dummy3: dummy3
})
*/
//fa.name = req.body.name;
console.log("Erzeugen der Instanz FA..");
//console.log(Dummy1);
//res.send(JSON.stringify(timestamp));
// create a new instance of the FA model
var fa = new FA(req.body);
//SAVE the new instance
fa.save(function(err) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("Instanz FA in Datenbank erzeugt!");
res.status(200);
res.json({ message: 'FA-Instance created in datbase!' });
}
});
})
// get all the FAs (accessed at GET http://localhost:8080/DNZ/FA)
.get(function(req, res) {
FA.find(function(err, fas) {
if (err)
res.send(err);
res.json(fas);
});
});
//on routes that end in /FA/:FA_id
//----------------------------------------------------
router.route('/FA/:FA_id')
// get the bear with that id
.get(function(req, res) {
FA.findById(req.params.bear_id, function(err, fa) {
if (err)
res.send(err);
res.json(fa);
});
})
/*
* Athlete.
find().
where('sport').equals('Tennis').
where('age').gt(17).lt(50). //Additional where query
limit(5).
sort({ age: -1 }).
select('name age').
exec(callback);
*/
// update the bear with this id
.put(function(req, res) {
FA.findById(req.params.FA_id, function(err, fa) {
if (err)
res.send(fa);
//bear.name = req.body.name;
/*
FA.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'FA updated!' });
});
*/
});
});
/*
// delete the bear with this id
.delete(function(req, res) {
FA.remove({
_id: req.params.bear_id
}, function(err, FA) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
*/
//*************************************************************************
//CREATE FP ROUTE
//*************************************************************************
router.route('/FP')
// create a FA (accessed at POST http://localhost:8080/DNZ/FP)
.post(function(req, res) {
//res.setHeader('Content-Type', 'application/json')
console.log("Erzeugen der Instanz FP..");
// create a new instance of the FP model
var fp = new FP(req.body);
//SAVE the new instance
fp.save(function(err) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("Instanz FP in Datenbank erzeugt!");
res.status(200);
res.json({ message: 'FP-Instance created in datbase!' });
}
});
})
// get all the FAs (accessed at GET http://localhost:8080/DNZ/FA)
.get(function(req, res) {
FP.find(function(err, fps) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
//res.send("Willkommen auf /FP");
res.json(fps);
}
});
});
//REGISTER OUR ROUTES -------------------------------and listen to requests
app.use('/DNZ', router);
//START THE SERVER
//=============================================================================
// set static directories
app.use(express.static('./dist'));
app.use(cors());
// Define Routes
var index = require('./routes/index');
var users = require('./routes/users');
//Set up routes
routes.init(app)
//run
app.listen(port);
console.log('Listen on port: ' + port);
console.log('Server started, Listening on port ', port);
This is primarily opinion based, but I had the same thing a while back and developed a way to extract route/model logic from the main file, using the module require-dir
In my app.js
/**
* Process ALL routes from routes dir utilising require-dir
*
* Allows us to include an entire directory, without replicating
* code, creating similar routes on a per end-point basis. This
* nicely keeps all end-point routes separate.
*/
var routes = requireDir('./routes');
for(var x in routes) {
application.use('/', routes[x]); // here, application is your express server instance
}
Then create a directory called routes and add whatever, for instance routes/branding.js:
var expressFramework = require('express');
var Branding = require('../models/branding');
var responseHelper = require('../shared/responseHelper');
var responseStatusCodes = require('../shared/responseStatusCodes');
var responseMessages = require('../shared/responseMessages');
var queryHelper = require('../shared/queryHelper');
var routerObject = expressFramework.Router();
var branding = new Branding();
var responsehelper = new responseHelper();
var queryhelper = new queryHelper();
/**
* Endpoint /branding/{chain_id}/{site_id}
*/
routerObject.get('/branding/:chain_id/:site_id', function(req, res, next) {
var requiredFields = [
{
chain_id: true, where: 'path'
},
{
site_id: true, where: 'path'
}
];
if (!queryhelper.authenticateToken(req.headers.authorization)) {
responsehelper.sendResponse(res, responseStatusCodes.STATUS_UNAUTHORISED,
responseMessages.RESPONSE_AUTHENTICATION_FAILED);
return;
}
if (!queryhelper.validateQuery(req, requiredFields)) {
responsehelper.sendResponse(res, responseStatusCodes.STATUS_INVALID_QUERY_PARAMS,
responseMessages.RESPONSE_INVALID_QUERY_PARAMS);
return;
}
branding.getBranding(req, function(err, results, pagination) {
if (err) return next(err);
if (results.length >= 1) {
responsehelper.sendResponse(res, responseStatusCodes.STATUS_OK, results);
} else {
responsehelper.sendResponse(res, responseStatusCodes.STATUS_NOT_FOUND,
responseMessages.RESPONSE_NO_RECORDS_FOUND);
}
});
});
module.exports = routerObject;
The key point here, is that you eventually export the express Router object, which your application, can 'use'. You'll also notice, that branding uses an include var Branding = require('../models/branding'); - This contains all the logic, whereas the route contains the end point definitions only, a snippet:
var Promise = require('bluebird');
var db = require('../shared/db');
var queryHelper = require('../shared/queryHelper');
var schemas = require('../schemas/schemas');
var _ = require('lodash');
var serverSettings = require('../shared/coreServerSettings');
// Create new instance of mysql module
var connection = new db();
var queryhelper = new queryHelper();
var queryAndWait = Promise.promisify(connection.query);
// Branding Object
var Branding = function(data) {
this.data = data;
};
Branding.prototype.data = {};
/**
* Branding methods
*/
Branding.prototype.getBranding = function(req, callback) {
var params = [];
var queryFoundRows = `select FOUND_ROWS() as total`;
var query = `select
id
from
company
where
1=1
and chain_id=?`;
params.push(req.params.chain_id);
queryAndWait(query + '; ' + queryFoundRows, params).then(function(result) {
return Promise.map(result[0], function(row) {
var params = [];
var query = `select
*
from
location
where
1=1
and company_id=?
and site_id=?`;
params.push(row.id);
params.push(req.params.site_id);
return queryAndWait(query, params).then(function(result) {
return result[0];
});
}).then(function(payload) {
callback(null, payload);
}).catch(function(err) {
callback(err, null, null);
});
});
};
module.exports = Branding;
May not be exactly what you're after, but should provide a good start point. Good luck!
This topic is subjective however - it is important to take a standard and stick to it. The way I handled this was by creating a subfolder with a module (using module.exports) and an init function that constructs the express app.
For every route I have another module that has an init function which accepts the express application as a parameter and then adds the routes in there.
Main code file:
var Api = require('./API/index.js');
File /API/Index.js:
var express = require('express');
/* Instantiations */
var app = express();
module.exports = {
...
apply();
...
}
var route1 = require('./Routes/route1.js');
var route2 = require('./Routes/route2.js');
/* all additional routes */
var Routes = [route1,route2,...]
function apply(){
for(var i=0;i<Routes.length;i++){
Routes[i].init(app);
}
}
Then in API/Routes/route1.js and API/Routes/route2.js...
module.exports = {
init: function(app){
/* add your route logic here */
}
}
The benefits of this approach in my experience is that you can optionally choose to add or remove routes as needed and it provides a readable route-path via the file system which is handy in most modern text editors.
server.js
var express = require('express');
var mysql = require('mysql');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require("method-override");
var request = require("request");
app.use(express.static(__dirname + '/public'));
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({'extended' : 'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json'}));
app.use(methodOverride());
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
port : 3306,
user : 'root',
password : 'xxxxxxx',
database : 'masterlist',
debug : false
});
//Rest APIs
app.get('/api/fetchmasterlist', function(req, res){
pool.getConnection(function(err, connection){
if(!err){
//Query
var strquery = "SELECT * FROM students";
connection.query(strquery, function(err, rows){
if(err){
res.json("Error in Query." + err);
}else{
res.json(rows);
}
});
}else {
//Return an Error
connection.release();
connection.destroy();
res.json("Error geting connection from DATABASE.");
return;
}
});
});
app.post('/api/addmasterlist', function(req, res){
pool.getConnection(function(err, connection){
if(!err){
//Query
/*var post = req.body.param;*/
var strquery = "INSERT INTO students(id, studentid, studentname, course, year) VALUES (?, ?, ?, ?, ?)";
connection.query(strquery, [req.body.id, req.body.studentid, req.body.studentname, req.body.course, req.body.year], function(err, rows){
if(err){
res.json("Error in Query." + err);
}else{
res.json("Success in inserting the new student." + rows);
}
});
}else {
//Return an Error
/*connection.release();
connection.destroy();*/
res.json("Error geting connection from DATABASE.");
return;
}
});
});
// application route
app.get('*', function(req, res){
res.sendfile('./public/index.html') // load the single static file
});
// listen
app.listen(8080);
console.log("App listening on port 8080");
my api/addmasterlist is not working and it gives me
Cannot GET /api/addmasterlist
error on the browser
using app.get on the masterlist seems to work fine and reflect on the database the problem is it will not work on my angular.js
okay using app.get seems to work but can anyone help me is this the proper way of pushing through nodejs? using angular
$scope.saveNewStudent = function(){
var dataa = $scope.studentmasterlist.push({
id: ($scope.studentmasterlist.length + 1),
studentid: $scope.studentid,
studentname: $scope.studentname,
course: $scope.course,
year: $scope.year,
});
$http.get('/api/addmasterlist', dataa).success(function(data, status) {
console.log('Data posted successfully');
})
//Clear the scope
$scope.studentid = "";
$scope.studentname = "";
$scope.course = "";
$scope.year = "";
}
The problem is that you declared your /api/addmasterlist endpoint as a POST request. Try changing it to GET and it might work as you expected.
Change this:
app.post('/api/addmasterlist', function(req, res){
To this:
app.get('/api/addmasterlist', function(req, res){
Alternatively, you can change your angular's http from get to post:
Change:
$http.get('/api/addmasterlist', dataa).success(function(data, status) {
to
$http.post('/api/addmasterlist', dataa).success(function(data, status) {
What i am trying to do ::
I am trying to move the uploaded file to /public/images
My request::
My app.js code
var express=require('express');
var mysql=require('mysql');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var app=express();
var connection=mysql.createConnection({
host:'localhost',
user:'******',
password:'******',
database:'*********'
});
connection.connect();
app.set('port',process.env.PORT||7002);
app.use(express.bodyParser());
app.post('/Details/',function(req,res){
var file_name=req.files.key.originalFilename;
console.log(file_name);
crypto.randomBytes(8, function(ex, buf) {
var array = req.files.key.originalFilename.split('.');
var type = array[array.length - 1];
var name = buf.toString('hex') + '.' + type;
fs.rename(req.files.key.path, './public/images/' + name, function(e) {
next(e, name);
});
});
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
Error i am facing::
next(e, name)......... "next" not defined
How to resolve this ?
What exactly do you want to do? I think that instead of calling next, you want to generate a response back to the client.
So instead of this:
next(e, name);
Do this:
if (e) {
res.send(500, e.message);
} else {
res.send(WHATEVER_YOU_WANT_TO_SEND_AS_RESPONSE);
}
If you really want to call next, you need to add it to the callback function's argument list:
app.post('/Details/', function(req, res, next) { ...