Node Js exiting after querying using Tedious package? - javascript

I am new to Node js and express. I trying to query my Azure database to get the list of patients(MR number). I am getting the list but I think the request.on() runs as an asynchronous function so first, it will render the HTML page without any list and after executing the function Node Js exit executing.
Code:
var express = require('express');
var router = express.Router();
//For database
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
function mrquery(connection) {
request = new Request(
"SELECT DISTINCT MRNO FROM Transaction_Record",
function(err, rowCount, rows) {
console.log(rowCount + ' row(s) returned');
process.exit();
}
);
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log(column.value);
});
});
connection.execSql(request);
}
/* GET home page. */
router.get('/', async function(req, res, next) {
var connection = req.app.get('connection');
var isconnected = req.app.get('isconnected');
if (isconnected) {
mrquery(connection)
res.render('index', {
title: 'Express'
});
} else {
console.log('Not Connected');
res.render('error', {
error: 'error'
});
}
});
module.exports = router;
Thanks in advance.

Related

"callback is not defined" in node js

This is part of my code, and it doesn't work. It says,
ReferenceError: callback is not defined
at C:\js\kweb-hw\routes\board.js:14:13
var express = require('express');
var router = express.Router();
var mysql_db = require('../db/db_con')();
var pool = mysql_db.init();
/* GET home page. */
router.get('/', function(req, res, next) {
pool.getConnection(function (err,conn) {
if(err) {
if(conn) {
conn.release();
}
callback(err,null);
return;
}
var sql = "SELECT * FROM board";
var exec = conn.query(sql,[] ,function(err, rows) {
conn.release();
if (err) throw err;
res.render('board', { rows: rows });
});
});
});
You don't need a callback in this case, because you're at the end of your route, so to speak.
So instead, you could do something like handle it with sending an error message to your rendered page.
var express = require('express');
var router = express.Router();
var mysql_db = require('../db/db_con')();
var pool = mysql_db.init();
/* GET home page. */
router.get('/', function(req, res, next) {
pool.getConnection(function (err,conn) {
if(err) {
if(conn) {
conn.release();
}
res.render('board',{rows: [],error:'Could not connect'});
}else{
var sql = "SELECT * FROM board";
var exec = conn.query(sql,[] ,function(err, rows) {
conn.release();
if (err) throw err;
res.render('board', { rows: rows });
});
}
});
});

Change a predefined value on server before a functional test

I'm looking to change requestHandler.value to 5 for my functional styled tests.
When running the suite, creating 1000 documents in the db is not really an option, so is it possible to change it's value programmatically before running the suite and then reset it afterwards? I can create 5 documents in db before the test to work with.
Of coarse I can stub countDocumentsInDb() in unit tests to return what I need, but I've simplified logic below for the sake of the question.
app.js:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var requestHandler = require('./lib/requestHandler.js');
var PORT = 4000;
app.route('/validate')
.get(function(req, res) {
requestHandler.process(req, res);
});
if (!module.parent) {
server.listen(PORT, function(err) {
if (err) {
return;
}
});
}
module.exports = app;
requestHandler.js:
var requestHandler = {
value: 1000,
process: function(req, res) {
numberOfDocumentsInDb = countDocumentsInDb();
if (numberOfDocumentsInDb === this.value) {
res.send(true);
} else {
res.send(false);
}
}
};
module.exports = requestHandler;
FVT style test ..
var Promise = require('promise');
var request = require('supertest');
var chai = require('chai');
chai.should();
var server = require('../../app.js');
describe('app.js', function() {
describe('/validate', function() {
it('should return true if number of documents in db matches pre-defined value', function(done) {
var fvtPromise = new Promise(function(fulfill) {
request(server)
.get('/validate')
.expect(200)
.end(function(err, res) {
if (err) {
throw err;
}
res.body.should.equal(true);
fulfill(null);
});
});
fvtPromise.done(function() {
done();
});
});
});
});
You can play with the require.cache, that will allow you to modify the values of requestHandler.
Is just an example I hope you get the idea.
- In the before each modify the require cache and set your test values
-In the after each set back the original values
-Please notice that the const server = require('./app.js'); is inside the test, so it will take the cache vales
e.g.
describe('test with cache', function(){
require('./requestHandler');
let originalValues;
beforeEach(function() {
originalValues = require.cache[ require.resolve('./requestHandler') ].exports;
require.cache[ require.resolve('./requestHandler') ].exports = {
value:5,
process: function(req, res) {
//other stuff
}
};
});
afterEach(function() {
require.cache[ require.resolve('./requestHandler') ].exports = originalValues;
});
it('should pass', function(){
const server = require('./app.js');
var fvtPromise = new Promise(function(fulfill) {
request(server)
.get('/validate')
.expect(200)
.end(function(err, res) {
if (err) {
throw err;
}
res.body.should.equal(true);
fulfill(null);
});
});
fvtPromise.done(function() {
done();
});
expect(true).to.be.true;
});
});

process.nextTick(function() { throw err; }); Error: Can't set headers after they are sent

I'm trying get data from MongoDB in a Node.js file.
I'm getting this error:
/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:719:10)
at ServerResponse.json (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:247:10)
at ServerResponse.send (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:152:21)
at /home/jay/node_project/user_data_manag/routes/api.js:42:13
at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:777:7
at handleCallback (/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:96:12)
at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:741:16
at handleCallback (/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:96:12)
at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:675:5
// Dependencies
var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;
var objectId = require('mongodb').ObjectID;
var assert = require('assert');
var url = 'mongodb://localhost/rest_test';
router.post('/user', function(req, res, next) {
if (req.body.name == "Login") {
var result = [];
mongo.connect(url, function(err, db) {
var data = db.collection('products').find();
data.forEach(function(doc, err) {
result.push(doc);
}, function() {
db.close();
res.send({
iteamd: result
});
});
});
} else {
res.send("data");
}
res.end();
});
//insert data
router.post('/put-data', function(req, res, next) {
var item = {
title: req.body.name,
content: req.body.sku,
author: req.body.price
};
var data = req.body.name;
mongo.connect(url, function(err, db) {
var cursor = db.collection('products').find({
"name": data
});
res.send(cursor.toString);
});
});
// Return router
module.exports = router;
Don't call res.send() and res.end() in the same request handler.
res.send() will call res.end() for you (source). res.end() is typically used after calling multiple res.write().
If /user POST is called multiple times and the POST n doesn't close the connection with db.close(); before the n+1 POST you could get the same error.
Just solved on my script.

returning data to index.js node express

Why is users undefined?
db.js:
var MongoClient = require('mongodb').MongoClient
var users;
MongoClient.connect('mongodb://127.0.0.1:27017/ExpressApp2', function(err, db) {
users = db.collection('usercollection');
users.find().each(function(err, doc) {
console.log(doc);
});
});
index.js
var express = require('express');
var router = express.Router();
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var users = require('../db').getUsers();
if (users==undefined)
res.send('undefined');
else
res.send('found something');
});
module.exports = router;
The collection is correctly retrieved from Mongo and logged to screen, but users in index.js gives undefined.
MongoClient.connect('mongodb://127.0.0.1:27017/ExpressApp2', function(err, db) {
users = db.collection('usercollection');
users.find().each(function(err, doc) {
console.log(doc);
});
});
should be
module.exports.getUsers = function() {
MongoClient.connect('mongodb://127.0.0.1:27017/ExpressApp2', function(err, db) {
return db.collection('usercollection');
});
}
I'm presuming that
users.find().each(function(err, doc) {
console.log(doc);
});
is part of your debugging and what you actually want to return is the user collection. The important bit is adding the block to module.exports as getUsers().
I got it to work with this async call in the end.
index.js
router.get('/userlist', function(req, res) {
var d = require('../db');
d.getUsers('input', function(users) {
users.each(function(err, doc) {
res.send(doc);
return false;
});
});
});
In db.js you are not using module.exports to export your users.
Your code in index.js suggests db.js exports an object with a getUsers function but it does not.

can't create a new directory using mongoose and express

Like the title entails.
I'm trying to make an application that when i put in certain info, it creates a link using mongoose _id. and express's app.get what i don't get is that to be able to join that directory i have to reload the whole server, which for the users and my sake a i don't want to do.
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var router = express.Router();
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
name: {
type: String,
unique: false
}
});
var collectionOfData = mongoose.model("dataType", collectedData);
io.on("connection", function (socket) {
socket.on("name", function (e) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
var Maindata = new collectionOfData({
ipAddress: ip,
name: e
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
});
app.get("/mix", function (req, res) {
collectionOfData.find(function (err, data) {
res.send(data);
});
});
collectionOfData.find(function (err, data) {
data.forEach(function (uniqueURL) {
app.get("/" + uniqueURL._id, function (req, res) {
res.send("<h1>Hello " + uniqueURL.ipAddress + "</h1><p>" + uniqueURL.name + "</p>");
});
});
});
http.listen(10203, function () {
console.log("Server is up");
});
So what i'm trying to do is make it so i don't have to reload the whole server, and i'm able to just join the created directory when it's done being loaded.
figured i should put a quick example:
localhost:10203/55c2b2f39e09aeed245f2996
is a link a user just created the long
55c2b2f39e09aeed245f2996
is the effect of the _id, but when the user try's to connect to that site it won't work until i reload the server and obviously i'd like to avoid that haha.
I have a index.html file, but all that has is a socket.emit that sends "name" to the server
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
app.get('/:uniqueURL', function(req, res){
var id = req.params.uniqueURL;
res.send("Your requested id : " + id);
})
Try to use this above.
You are creating fix get path inside collectionData.find. That is the problem. So each time you have to reload the server by restarting.

Categories