Cannot read property 'end' of undefined - MySQL , NodeJS - node.js

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?

Related

Sample Hello World Express App is returning binary data

The following doesnt seem to work. It's simple Express sample code. You can ignore the other responses. Im just trying to get the basic '/' home page working and that's refusing to work. Code is as follows:
var express = require('express');
var sR = require('./routes/index');
var path = require('path');
var urlencoded = require('url');
var bodyParser = require('body-parser');
var json = require('json');
var methodOverride = require('method-override');
var jade = require('jade');
var fs = require('fs');
var http = require('http2');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dbLoc = 'mongodb://localhost:27017';
const dbName = 'gothamDB';
var dbConn = null;
const dbURL = "mongodb://gotthamUser:abcd1234#localhost:27017/gothamDB"
const mongoClient = new MongoClient(dbURL, { useNewUrlParser: true, useUnifiedTopology: true});
// Use connect method to connect to the server
dbConn = mongoClient.connect(function(err, client) {
assert.strictEqual(null, err);
console.log("Connected successfully to server");
dbConn = client;
});
var app = express();
app.set('port', 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', jade);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.set('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});
app.post('/create_collection', function(req, res){
var db = dbConn.db('gothamDB');
var userData = db.createCollection(req.body.coll_name, function(err){
if(err){
res.send('Error creating database: ' + req.body.coll_name);
return;
}
res.send('Database ' + req.body.dbname + ' created successfully');
});
});
app.post('/new_contact', function(req, res){
var name = req.body.name;
var phone = req.body.phone;
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
collection.insert(
{name : name, phone: phone}
, function(err, result) {
assert.strictEqual(err, null);
assert.strictEqual(1, result.result.n);
assert.strictEqual(1, result.ops.length);
res.send("Inserted new record into the collection");
});
});
app.post('view_contact', function(req, res){
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
coll.find({'phone' : req.body.phone}).toArray(function(err, docs){
if(err) {
res.send("Error looking up the data");
return;
}
res.send(docs);
return;
});
});
app.post('delete_contact', function(req, res){
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
coll.deleteOne({'phone' : req.body.phone}).toArray(function(err, docs){
if(err) {
res.send("Error looking up the data");
return;
}
res.send(docs);
return;
});
});
//const key = path.join(__dirname + '/security/server.key');
//const cert = path.join(__dirname + '/security/server.crt');
const options = {
key: fs.readFileSync(__dirname + '/security/server.key'),
cert: fs.readFileSync(__dirname + '/security/server.crt')
}
http.createServer(app).listen(app.get('port'), function(err){
console.log('Express server lisetning on port ' + app.get('port'));
})
console.log("Server started");
Any clue? Browser shows as follows:
Itt's showing an ERR_INVALID_HTTP_RESPONSE
if I run a curl command, it shows the following:
NodeExample % curl -X GET 'http://localhost:8080/'
Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file
If I put a breakpoint at the line:
res.send("Hello World");
that never hits. I've also tried putting in
res.header("Content-Type", "application/json");
but since the breakpoint never hits, it is not going to help I guess.
You are using set here
app.set('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});
It should be get
app.get('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});

How to get rid of Socket Error problem in postman using nodejs API's for login and signup

I am new to Node.js and trying to create a login and signup API's and storing these data in MongoDB, but when I post the signup request I get error Socket Hangup (Could not get Response). I have tried a lot but didn't able to debug why I am getting this problem.
Here is my app.js code
'use strict'
var createError = require('http-errors');
var express = require('express');
var path = require('path');
const fs=require('fs');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mongoose=require('mongoose');
const Dishes=require('./Model/schema');
const session=require('express-session');//used for creating the session
const FileStore=require('session-file-store')(session);//used to create the file for the storage of cookies
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
//var promoRouter = require('./routes/promoRouter');
//var leaderRouter = require('./routes/leaderRouter');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Sauravpandey:85ffxufexfEP3HXzPPq#saurav-5irg5.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true,useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
console.log('conected properly to drive');
// perform actions on the collection object
client.close();
});
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session({
name:'session-id',
secret:'12345-67890-09876-54321',
saveUninitialized:false,
resave:false,
store:new FileStore()
}))
app.use('/', indexRouter);
app.use('/users', usersRouter);
//app.use(cookieParser('12345-67890-09876-54321'));
///////////////////----------------authorization process-----------------------////////////////////
function auth (req, res, next) {
console.log(req.session);
if(!req.session.user){
var err = new Error('You are not authenticated!');
err.status=403;
return next(err);
}
else{
if(req.session.user==='authenticated'){
next();
}
else{
var err = new Error('You are not authenticated!');
err.status = 403;
return next(err);
}
}
}
app.use(auth);
app.use(express.static(path.join(__dirname, 'public')));
// modifications done
app.use('/dishes',dishRouter);
// catch 404 and forward to error handler
app.all('/',(req,res,next)=>{
res.statusCode=200;
res.setHeader('Content-Type','text/plain');
next();
});
app.listen(3000,()=>console.log("Server is started listening at port 3000"));
Here is user.js file-
var router = express.Router();
var mongoose=require('mongoose');
var User=require('../Model/user');
var bodyParser=require('body-parser');
router.use(bodyParser.json());
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
//------------------------------------- SignUp-----------------------///////////////////
router.post('/signup',(req,res,next)=>{
User.findOne({username:req.body.username})
.then((user)=>{
if(user!=null){
var err=new Error('this user '+ req.body.username +' already exists');
err.status=403;
next(err);
}
else{
return user.create({
username:req.body.username,
password:req.body.password
});
}
})
.then(user=>{
res.statusCode=200;
res.setHeader('Content-Type','application/json');
res.json({status:'Registration sussesful',user: user});
}), (err)=>next(err)
.catch((err)=>next(err));
});
//---------------------------- Login Code-----------------------------------------------
router.post('/login',(req,res,next)=>{
if(!req.session.user){
var authHeader=req.headers.authorization;
if(!authHeader){
var err=new Error('You are not authenticated!');
res.setHeader('WWW-Authenticate','Basic');
err.status=401;
return next(err);
}
var auth=new Buffer.from(authHeader.split(' ')[1],'base64').toString().split(':');
var username=auth[0];
var password=auth[1];
User.findOne({username:username})
.then((user)=>{
if(user===null){
var err=new Error('User '+username +' does not exist');
err.status=403;
return next(err);
}
else if(user.password!=password){
var err=new Error('Your password is incorrect');
err.status=403;
return next(err);
}
else if(user.username===username&&user.password===password){
req.session.user='authenticated';
res.statusCode=200;
res.setHeader('Content-Type', 'text/plain');
res.end('You are authenticated!')
}
}).catch((err)=>next(err));
}
else{
res.status=200;
res.setHeader('Content-Type','text/plain');
res.end('You are already authenticated');
}
});
//--------------------------------- Logout code-------------------------------------------
router.get('./logout',(req,res)=>{
if(req.session){
req.session.destroy();
res.clearCookies('session_id');
res.redirect('/');
}
else{
var err = new Error('You are not logged in!');
err.status = 403;
next(err);
}
});
module.exports = router;```
I have created the schemas properly I think there is some error in app.js or users.js file.

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
...
}

TypeError: "Object is not a function" when using a constructor

I am making a user registration form witch insert a record to the mongodb. I am using there fore:
MongoDB version v2.6.11
NodeJS version v0.10.25
Express version 4.13.1
All works fine except when a use a constructor var newUser = new User({...}); it returns the error Object is not a function
The rest works fine. I get the logging before it returns the error but i don't know how to fix this.
users.js
var express = require('express');
var router = express.Router();
var User = require('../models/user');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/Registreren', function(req, res, next) {
res.render('Registration', { title: 'Registreren' });
});
router.get('/Aanmelden', function(req, res, next) {
res.render('Aanmelden', { title: 'Aanmelden' });
});
router.post('/Registreren', function(req, res, next){
// Get form value
console.log('Bericht in behandeling ...')
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password_confirm = req.body.password_confirm;
console.log('username: ' + username);
console.log('email: ' + email);
console.log('password: ' + password);
console.log('password_confirm: ' + password_confirm);
console.log('FIRST TEST: ' + JSON.stringify(req.file));
console.log('SECOND TEST: ' + req.file.profileimage);
console.log('THIRD TEST: ' + req.file.originalname);
// Check for image field
if (req.file || req.file.profileImage){
console.log('Uploading file....');
//File Info
var profileImageOrginalName = req.file.originalname;
var profileImageName = req.file.name;
var profileImageMimetype = req.file.mimetype;
var profileImagePath = req.file.path;
var profileImageExt = req.file.extension;
var profileImageSize = req.file.size;
} else{
console.log('profileImageFile not found....');
// Set default image
var profileImageName = 'noimage.png';
}
// Form validation
req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkBody('email','email is verplicht').notEmpty();
req.checkBody('email','email is niet geldig').isEmail();
req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkBody('password','Wachtwoord is verplicht').notEmpty();
req.checkBody('password_confirm','Wachtwoorden zijn niet `gelijk').equals(req.body.password);`
// Error handling
var errors = req.validationErrors();
console.log(errors);
if(errors){
console.log('Error handling....');
res.render('Registration',{
errors: errors,
email: email,
username: username,
password: password,
password_confirm: password_confirm
});
} else {
console.log('Make new User ....');
console.log('email: ' + email);
console.log('username: ' + username);
console.log('password: ' + password);
console.log('profileImageName: ' + profileImageOrginalName);
var newUser = new User({
email: email,
username: username,
password: password,
profileimage: profileImageOrginalName
});
console.log('---------------- START TEST----------------------------');
console.log('FIRST TEST: ' + JSON.stringify(newUser));
console.log('SECOND TEST: ' + newUser);
// Create User
User.createUser(newUser, function(err,user){
if(err) throw err;
});
// Succes message
req.flash('succes','Je bent succesvol aangemedld');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
APP.JS
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var methodOverride = require('method-override');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle file Uploads
app.use(multer({dest:'./uploads/'}).single('profileimage'));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Vallidator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Flash
app.use(flash());
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
user.js
console.log('Mongoose Start....');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Users');
var db = mongoose.connection;
db.once('open', function (callback) {
//user Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
},
email: {
type: String,
},
profileimage: {
type: String,
}
});
console.log('Create record!');
var User = module.exports = mongoose.model('User',UserSchema);
module.exports.createUser = function(newUser, callback){
newUser.save(callback);
console.log('USER: ' + newUser)
};
});
What i have tried an read
I have read the following post:
Node.js: object is not a function
node.js express.js object is not a function call_non_function
TypeError: object is not a function Node.js
I have tried to build more logging as you can see in the scripts so i can pin point where the problem come from. But i don know how to fix this. I hope you can help me.

Can't receive response with 503 error (Service Unavailable) in aws-sdk(node.js)

app.js
var express = require('express');
var express_namespace = require('express-namespace');
var path = require('path');
var favicon = require('serve-favicon');
var http = require('http');
var https = require('https');
var e_logger = require('morgan');
var logger = require('./logger.js').getLogger('framework');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var awsControl = require('./routes/awsControl')
var aws = require('aws-sdk');
var ec2 = new aws.EC2();
var app = express();
var server = http.createServer(app);
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.set('port', 80);
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(cookieParser());
app.use(e_logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use('/', routes);
}
// routes
app.namespace('/', function () {
app.get('describeInstances', awsControl.describeInstances);
});
server.listen(app.get('port'), function () {});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404
logger.error(err);
next(err);
});
awsControl.js
var aws = require('aws-sdk');
var util = require('util');
aws.config.update({
accessKeyId: "myKey",
secretAccessKey: "mySecretKey",
region: "ap-northeast-1"
});
console.log("config = " + util.inspect(aws.config));
var ec2 = new aws.EC2({ region: "ap-northeast-1" });
var app01 = 'aaaaaaaa';
var DB01 = 'bbbbbbbb';
exports.describeInstances = function (req, res) {
var params = {
Filters: [{
Name: 'vpc-id',
Values: ['vpc-cccccccc']
}],
DryRun: false
};
ec2.describeInstances(params, function (err, data) {
if (err) { // an error occurred
console.log(err, err.stack);
} else { // successful response
console.log(data);
}
});
}
control.js
var Control = function () {
this.initializePage();
};
Control.prototype = new Object();
Control.prototype = {
initializePage : function () {
$.ajax({
type: "GET",
url: "describeInstances",
success : function (data, status, jQxhr) {
console.log("### describeInstances success");
console.log(data);
},
error : function (jQxhr, status, error) {
console.log("### describeInstances error");
console.log(error);
console.log(jQxhr);
},
complete : function (jQxhr, status) {
console.log("### describeInstances complete");
console.log(jQxhr);
}
});
}
}
I programmed like above and the node web server is operating well.
awsControl.js is server-side javascript and control.js is client-side javascript.
When I connect to my web server, Control class is called first.
Here is the trouble. When I send request with startInstance (AWS-SDK API), it's working in server-side.
However, I can't receive response with 503 error(service unavailable).
On client-side, I always receive error callback with 503 error.
I don't know why I can't receive response.
I set security groups(EC2) and NACL(VPC) up so I don't think that it's firewall trouble.
Is there anybody can tell me how I can find the solution out?
I have done this.
ec2.describeInstances(params, function (err, data) {
if (err) { // an error occurred
console.log(err, err.stack);
} else { // successful response
console.log(data);
res.send(data); <-- this line
}
});
I added just a line I focus to awsControl.js file, then done.

Resources