What is the best way to pass information from app.js? - node.js

In the code below, what is best way to pass information from app.js to choices.js ?
Currently, I put them all in a variable called answer.
Is that the best way to do it ?
Thank you.
These are the code in app.js:
var express = require("express");
var cors = require("cors");
var bodyParser = require("body-parser");
var app = express();
var sql = require('msnodesqlv8');
:
var choicesTerm = [];
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res, next) {
console.log(`${req.method} request for '${req.url}' -
${JSON.stringify(req.body)}`);
next();
});
var connStr = "Driver={SQL Server Native Client 11.0};....";
sql.open(connStr, function (err, conn) {
var pm = conn.procedureMgr();
pm.callproc('mySP',sessionID, function (err, results) {
:
pm.callproc('mySp2', function (err, results) {
:
if (results.length)
{
var row = results[0];
var Answers = [];
Answers = row.Answers.split("|");
for (var i = 0, len = Answers.length; i < len; i++) {
var answer = {value: Answers[i], description: Answers[i], question: row.text, detail: row.detail}; //--> pass information to choices.js
choicesTerm[i] = answer;
}
}
})
});
});
app.use(express.static("./public"));
app.use(cors());
app.get("/choices-api", function(req, res) {
res.json(choicesTerm);
});
These are the code in choices.js:
$(document).ready(function () {
$.getJSON('/choices-api', printTerms);
});
function printTerms(terms) {
var question = terms[0].question; //--> This is passed from app.js
var detail = terms[0].detail; //--> This is passed from app.js
}

Related

How to get data from another route (POST method)?

I have multiple routes setup. I want to get specific data from another route. That data is coming from a post method.
My server.js look like this:
var mysql = require('mysql')
var morgan = require('morgan')
var cors = require('cors')
var bodyParser = require('body-parser')
var http = require('http')
var dateFormat = require('dateformat')
const port = process.env.PORT || 3000;
//middleware
var app = express()
app.use(cors())
app.use(morgan('dev'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}))
var now = new Date()
//routes
var user_details = require('./routes/users')
var user_orders = require('./routes/order')
//Use routes
app.use('/', user_details)
app.use('/', user_orders)
//Launch Server
app.listen(port, () => {
console.log('Server start at port: ' + port)
})
My routes/users.js :
var router = express.Router()
var db = require('../dbConfig')
var randomstring = require("randomstring");
var moment = require('moment')
router.post('/list', (req, res) => {
var appendRandomString = randomstring.generate({
length: 10,
capitalization: 'uppercase',
readable: true
})
var id = 'PEPPR_' + appendRandomString
var email = req.body.email
var listItems = req.body.listItems
var listTitle = req.body.listTitle
var date = moment().format("Do MMMM YYYY");
var time = moment().format("LT");
const INSERT_USER_LISTS = `INSERT INTO user_lists (id,date,time,user_email,list_title,list_items) VALUES('${id}','${date}','${time}','${email}','${listTitle}','${listItems}')`
db.query(INSERT_USER_LISTS, (err, success) => {
if (err) {
return res.send(err)
} else {
console.log('list added')
res.send('list added')
}
})
})
module.exports = router
And my routes/order.js
var router = express.Router()
var db = require('../dbConfig')
var randomstring = require("randomstring");
var moment = require('moment')
var user_details = require('./users')
router.post('/sendOrder', (req, res) => {
var email = req.body.email
var status = 'Order Confirmed'
var date = moment().format("Do MMMM YYYY");
var time = moment().format("LT");
var appendRandomString = randomstring.generate({
length: 10,
capitalization: 'uppercase',
readable: true
})
var id = 'PEPPR_ORDER_' + appendRandomString
var list_items = ''
var list_title = ''
var data = {
id: id,
email: email,
list_items: list_items,
list_title: list_title,
date: date,
time: time,
status: status
}
const CREATE_ORDER = `INSERT INTO user_orders SET ?`
db.query(CREATE_ORDER, data, (err, success) => {
if (err) {
return res.send(err)
} else {
res.send('oc')
}
})
})
module.exports = router
I want the list_items and list_title in my order.js from users.js , this two data is coming from a POST method as you can see in users.js
If I understood you correctly you want to use request body which comes to /users in another route /orders.
You are saving user data list_title and list_item in users table. So all you need to access the data from /orders route is make an additional query to db where you will select users by id\email.
Not sure which db ORM you use but in general cases your code may look like this:
router.post('/sendOrder', async (req, res) => {
const { email } = req.body;
// declare other fields
const user = await db.query(
`SELECT * FROM users WHERE email LIKE '%${email}%'`,
(err, success) => {
if (err) {
return res.send(err);
} else {
res.send('ok');
}
}
);
// declare `data` object with user.list_title, user.list_item
const CREATE_ORDER = `INSERT INTO user_orders SET ?`;
db.query(CREATE_ORDER, data, (err, success) => {
if (err) {
return res.send(err);
} else {
res.send('ok');
}
});
});

Cannot read property 'end' of undefined - MySQL , NodeJS

I want to show you my error with NodeJS and MySQL.
Error is at line 45 of app.js
Cannot read property 'end' of undefined
at ServerResponse.<anonymous> (/usr/my_server/app.js:45:24)
It happen when I call a request from 'addReferFriend.js' file.
I link here the two files that I am using.
app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql= require('mysql2');
var http = require('http');
var app = express();
var addReferFriend = require('./addReferFriend');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(async function(req, res, next) {
try {
if( req.dbConnection ) {
// ensure that req.dbConnection was not set already by another middleware
throw new Error('req.dbConnection was already set')
}
let connection = mysql.createConnection({
host: 'xx',
user: 'xx',
password: 'xx',
database: 'xx'
});
res.on("finish", function() {
// end the connection after the resonponse was send
req.dbConnection.end()
});
// wait for the connection and assign it to the request
req.dbConnection = await connection.connect();
next();
} catch(err) {
next(err);
}
});
app.use('/api/addReferFriend', addReferFriend);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
var server = http.createServer(app);
server.listen(3955);
addReferFriend.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.post('/', function(req, res, next) {
var uid = req.body.uid;
var friendReferCode = req.body.friendReferCode;
var sqlCheckIfExist = "SELECT my_refer FROM hub_user WHERE my_refer = '" + friendReferCode + "'";
var sqlCodeCheckSameAsMine = "SELECT my_refer FROM hub_user WHERE uid = '" + uid + "'";
function checkIfUserCodeExist() {
return req.dbConnection.query(sqlCheckIfExist)
.then(([rows, fields]) => {
if (rows == 0) {
console.log("Non esiste!")
return res.send(JSON.stringify({
"status": 500,
"response": "codeNotExist"
}));
}
console.log("Esiste!")
return checkIfCodeIsSameAsMine(connection)
})
}
function checkIfCodeIsSameAsMine() {
return req.dbConnection.query(sqlCodeCheckSameAsMine)
.then(([rows, fields]) => {
if (rows == friendReferCode) {
console.log("Codice uguale!")
return res.send(JSON.stringify({
"status": 500,
"response": "sameCodeAsMine"
}));
}
console.log("Codice non uguale!")
})
}
checkIfUserCodeExist()
.catch(next)
});
module.exports = router;
I have no idea how fix this type of problem. It happen when I call the checkIfUserCodeExist() and it doesn't join into the function and it gives directly the error. I can't print any of console.log because it break.
Hope that somebody can help me with this issue.
Thanks in advance for the help,
Michele.
it seems to be req.dbConnection.end() the problem... the object dbConnection is undefined.
is it possible that the connection is closed first for some reason? so the point to closing connection is not correct?

MEAN API using node-restful no response

I'm trying to setup API for multiple projects that use same database structure (running on same CMS) but when I'm trying to reach some data I get no response.
index.js
var express = require("express");
var cors = require("cors");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var _ = require("lodash");
var passport = require("passport");
var dbconfig = require("./app/config/database");
// Create the application
var app = express();
var user = require("./app/routes/User");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
var connections = [];
// Auto CORS
app.use(cors());
/* Mnual CORS Start
app.use(function(req, res, next){
res.header("Access-Controll-Allow-Origin", "*");
res.header("Access-Controll-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Controll-Allow-Headers", "Content-Type");
next();
});
/* Manual Cords end */
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
require("./app/config/passport")(passport);
app.get("/", (req, res) => {
res.json({ msg: "Nothing here mate" });
});
//------------ THIS IS WORKING ----------------
app.get("/db/:database/navigation", (req, res) => {
var dbname = req.params.database;
var conn = connections[dbname];
var navs = conn.model("navigation", app.models[dbname].navigation);
// Send json data/error
if (navs) navs.find({}, (err, data) => res.json(data));
else res.json({ error: true, msg: "Model not found" });
});
// -------------------------------------------------------
// Setup databases for all projects
_.each(dbconfig.databases, db => {
var appModels = require("./app/models/index");
var processed = 0;
// We will use prefix for all routes /db/:database/
var routePrefix = "/db/" + db.name;
// Use user section
app.use(routePrefix + "/user", user);
// Connection callback - we need to wait for modules to initialize
var connect = () => {
// Initialize connection
connections[db.name] = new mongoose.Mongoose().createConnection(db.url);
// Create some callbacks
connections[db.name].on("connected", () => { console.log("Connected to database " + db.url); });
connections[db.name].on("error", onDatabaseError)
// Once we initialize connection, we need to setup all routes
connections[db.name].once("open", function () {
// Load routes
var routes = require('./app/routes');
// Loop trough routes and use all of them
_.each(routes, function (controller, route) {
var newRoute = routePrefix + route;
app.use(newRoute, controller(app, newRoute, db.name));
});
});
};
// Initialize models
_.each(appModels, (model, index) => {
// Create object if doenst exist
if (app.models == null)
app.models = {};
if (app.models[db.name] == null) {
app.models[db.name] = { [model.name]: model.model };
}
else {
app.models[db.name] = Object.assign(app.models[db.name], { [model.name]: model.model });
}
processed++;
// if this was the last process we are ready to connect
if (processed === appModels.length)
connect();
});
});
app.listen(3000);
app/models/index.js
module.exports = [
{
name: "navigation",
model: require('./Navigation.js')
},
...
];
app/routes.js
module.exports = {
'/navigation': require('./controllers/NavigationController'),
....
};
app/controllers/NavigationController.js
var restful = require("node-restful");
module.exports = function(app, route, dbname){
console.log(route);
var rest = restful.model(
"navigation",
app.models[dbname].navigation
).methods(['get', 'put', 'post', 'delete']);
rest.register(app, route);
// Return middleware
return function(req, res, next){
next();
};
};
Navigation.js is basically just a schema. If I set up route manually like this:
app.get("/db/:database/navigation", (req, res) => {
var dbname = req.params.database;
var conn = connections[dbname];
var navs = conn.model("navigation", app.models[dbname].navigation);
// Send json data/error
if (navs) navs.find({}, (err, data) => res.json(data));
else res.json({ error: true, msg: "Model not found" });
});
it works just fine. I guess I need to assign connection somewhere to restful but I have no idea where. If I use single connection with mongoose.connect() everything works perfectly, but that's not what I need :)
Does anyone have any idea what to do next to get this to work? Will appreciate any help, thanks.
Kind of dug into it and made an extension to change driver reference
Here are all the changes, hope it helps someone in future :)
extensions/restful/index.js
var restful = require("node-restful"),
model = require("./model"),
mongoose = require('mongoose');
exports = module.exports = restful;
exports.model = model;
exports.mongoose = mongoose;
extensions/restful/model.js
exports = module.exports = model;
exports.changeDriver = function(driver){
mongoose = driver;
}
// original model function from node-restful/lib/model.js
function model() {
var result = mongoose.model.apply(mongoose, arguments),
default_properties = defaults();
if (1 === arguments.length) return result;
for (var key in default_properties) {
result[key] = default_properties[key];
}
return result;
}
app/controllers/navigation.js
var restful = require("../extensions/restful");
module.exports = function(app, route, db)
{
restful.model.changeDriver(db.mongoose);
// Setup controller REST
var rest = restful.model(
"navigation",
app.models[db.name].navigation
).methods(['get', 'put', 'post', 'delete']);
// Register this endpoint with the application
rest.register(app, route);
// Return middleware
return function(req, res, next){
next();
};
};
index.js
....
var connect = () => {
// Initialize connection
var $db = databases[_db.name] = {
mongoose: new mongoose.Mongoose(),
name: _db.name
};
$db.mongoose.connect(_db.url);
// Create some callbacks
$db.mongoose.connection.on("connected", () => { console.log("Connected to database " + _db.url); });
$db.mongoose.connection.on("error", (err) => { console.log("Database error: " + err); });
// Once we initialize connection, we need to setup all routes
$db.mongoose.connection.once("open", function () {
// Custom routes for user section
var userRoutes = new UserRoutes($db.mongoose);
app.use(routePrefix + "/user", userRoutes.getRouter());
// Load routes
var routes = require('./app/routes');
// Loop trough routes and use all of them
_.each(routes, function (controller, route) {
var newRoute = routePrefix + route;
app.use(newRoute, controller(app, newRoute, $db));
});
});
};
....

callback not fetching record in nodejs

i want to pass email in postman and want to print the fetched json data to console. but it is not fetching any data. so help me to solve this issue
mongoconnect.js
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo=null;
exports.connection=function(){
if(dbo!=null) return
MongoClient.connect(url, function(err, db) {
if (err) throw err;
dbo = db.db("hospital_api");
});
}
var get = function (){
return dbo;
}
exports.email=function(r){
get().dbo.collection("doctor").find({"email":r}).toArray(function(err,result)
{
if(err) throw err;
console.log(result)
return result;
})
}
doctor.js
var express = require('express');
var router = express.Router();
var bodyParser = require("body-parser");
var validator = require('validator');
var mongo= require('./mongoconnect')
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/',function(req,res)
{
d=mongo.email(req.body.email)
console.log(d);
})
module.exports = router;
In export.email, you have a typo
exports.email = function(r) {
get().collection("doctor").find({"email":r}) // no ".dbo" after get()

Node.js Retrieve URL Parameters from Server

I need to pass a parameter (qItems) in XMLHttpRequest.open:
index.html (app.listen(8080);)
var qItems= 8;
var url= 'ItemsList';
var xhr = new XMLHttpRequest();
var tag = document.getElementById("insertHere");
tag.innerHTML = "Loading...";
xhr.open("GET", url+"?qItems="+qItems, true);
xhr.onreadystatechange = function() {
display(tag, xhr);
}
xhr.send(null);
But on Server side (server.js) use static URLs:
var express = require('express');
var bodyParser = require('body-parser');
var directory = require('serve-index');
var sqlite3 = require('sqlite3').verbose();
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('views', __dirname);
app.set('view engine', 'pug');
var db = new sqlite3.Database('./data/DB.sqlite',function(err){
if (err) {
console.log(err.message);
}
console.log('Connected to DB!');
});
app.get('/ItemsList', function(req, res) {
db.all("SELECT rowid, iName, iDescrip FROM Items", function(err, row) {
if (err !== null) {
res.status(500).send("An error has occurred: " + err);
} else {
res.render('ItemsList.pug', {
items: row
}, function(err, html) {
res.status(200).send(html)
});
}
});
});
I try (server.js):
app.get('/ItemsList?qItems='+qItems, function(req, res) {...}
But I get error: qItems undefined (from node.js)
Is there any way to get query parameters from Server side?
You don't need to implement a different handler for url with query params, ItemsList/qItems=xxx, query params are available to /ItemsLists GET handler in req.query.
app.get('/ItemsList', function(req, res) {
// You can access qItems from query params
var qItems = req.query.qItems
...
}

Resources