Remove name file html from url - javascript

I am using Angular JS for my Front End and Express Server for backend.
I am trying to remove the init.html from my url.
I have read other post and I have not managed to fix it.
Now : http://localhost:3000/init.html#!/export
I want look like : http://localhost:3000/#!/export
I tried : $locationProvider.hashPrefix() and
locationProvider.html5Mode(true) but it is not working.
manager-app.js
angular.module("ManagerApp", ["angularUtils.directives.dirPagination", "ngRoute"]).config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/index.html"
})
.when("/export", {
templateUrl: "export/listExport.html",
controller: "ListCtrlExport"
});
index.html is a static html
init.html
<html ng-app="ManagerApp">
<head>
<title>
ManagerApp
</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css" type="text/css" />
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="/bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="/bower_components/angularUtils-pagination/dirPagination.js"></script>
<script type="text/javascript" src="/bower_components/bootbox.js/bootbox.js"></script>
<script type="text/javascript" src="/manager-app.js"></script>
<script type="text/javascript" src="/export/list-ctrl.js"></script>
<script type="text/javascript" src="/export/edit-ctrl.js"></script>
</head>
<body>
<ng-view></ng-view>
</header>
</body>
</html>
index.js
var express = require("express");
var bodyParser = require("body-parser");;
var helmet = require("helmet");
var path = require('path');
var app = express();
var folder = path.join(__dirname, '/public');
var MongoClient = require('mongodb').MongoClient;
var mURL = "mongodb://XXXXXXXXXXXXXXXXXxXXXXXXXX";
var port = (process.env.PORT || 10000);
var BASE_API_PATH = "/api/v2";
var moduleExport = require("./api/v2/exportModule.js");
var dbAlberto;
var dbUser;
app.use("/", express.static(path.join(__dirname, "public")));
app.use(bodyParser.json()); //use default json enconding/decoding
app.use(helmet()); //improve security
app.use("/",express.static(path.join(__dirname, 'public')));
app.use("/api/v2/tests", express.static(path.join(__dirname , "public/test.html")));
MongoClient.connect(mURL, {
native_parser: true
}, function(err, database) {
if (err) {
console.log("CANNOT connect to database" + err);
process.exit(1);
}
dbAlberto = database.collection("exports");
dbUser = database.collection("user");
moduleExport.register(app, dbAlberto, dbUser, BASE_API_PATH);
app.listen(port, () => {
console.log("Magic is happening on port " + port);
});
});
exportModule
var exports = module.exports = {};
exports.register = function(app, dbAlberto, dbUser, BASE_API_PATH) {
// Authentication apikey
var key = function(request, callback) {
var d;
dbUser.find({
apikey: request
}).toArray(function(err, sExport) {
if (sExport.length > 0) {
d = 1;
}
else {
d = 0;
}
callback(d);
});
}
function searchFrom(sExport,from,to){
var from = parseInt(from);
var to = parseInt(to);
var res=[];
sExport.forEach((filt)=>{
if(filt.year>=from && filt.year<=to){
res.push(filt);
}
});
return res;
// GET a collection and Search
app.get(BASE_API_PATH + "/export-and-import", function(request, response) {
var url = request.query;
var province = url.province;
var year = url.year;
var importS = url.importS;
var exportS = url.exportS;
var off = 0;
var limite = 100;
var res = request.query.apikey;
var from = url.from;
var to = url.to;
var resul = key(res, function(d) {
if (d > 0) {
if (url.limit != undefined) {
limite = parseInt(url.limit);
off = parseInt(url.offset);
}
if (from != undefined && to != undefined) {
dbAlberto.find({}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
var filted=searchFrom(sExport,from,to);
response.send(filted);
}
else {
console.log("WARNING: There are not any stat with this properties");
response.sendStatus(404); // not found
}
}
});
}
else {
dbAlberto.find({}).skip(off).limit(limite).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
var filted = sExport.filter((stat) => {
if ((province == undefined || stat.province == province) && (year == undefined || stat.year == year) && (year == undefined || stat.year == year) && (importS == undefined || stat.importS == importS) && (exportS == undefined || stat.exportS == exportS)) {
return stat;
}
});
if (filted.length > 0) {
console.log("INFO: Sending stat: " + JSON.stringify(filted, 2, null));
response.send(filted);
}
else {
console.log("WARNING: There are not any stat with this properties");
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
// LoadInitialData
app.get(BASE_API_PATH + "/export-and-import/loadInitialData", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
dbAlberto.find({}).toArray(function(err, stats) {
if (err) {
console.error('WARNING: Error while getting initial data from DB');
return 0;
}
if (stats.length === 0) {
var initialStats = [{
"province": "jaen",
"year": "2013",
"oil": "375",
"importS": "802",
"exportS": "274"
}];
dbAlberto.insert(initialStats);
console.log("Date insert in db");
response.sendStatus(201, BASE_API_PATH + "/");
}
else {
console.log('INFO: DB has ' + stats.length + ' objects ');
response.sendStatus(200);
}
});
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
/*
// GET a collection
app.get(BASE_API_PATH + "/export-and-import", function(request, response) {
console.log("INFO: New GET request to /export-and-import");
dbAlberto.find({}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
console.log("INFO: Sending export and import stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
});
});
*/
// GET a single resource
app.get(BASE_API_PATH + "/export-and-import/:province", function(request, response) {
var province = request.params.province;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province) {
console.log("WARNING: New GET request to /export-and-import-stats/:name without name, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New GET request to /export-and-import-stats/" + province);
dbAlberto.find({
province: province
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
console.log("INFO: Sending stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
else {
console.log("WARNING: There are not any export stats with name " + province);
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//GET all stats of one year
app.get(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province) {
console.log("WARNING: New GET request to /export-and-import/ without province, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New GET request to /export-and-import/" + province);
dbAlberto.find({
province: province,
year: year
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
console.log("INFO: Sending stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
else {
console.log("WARNING: There are not any export stats with name " + province + " and " + year);
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//POST over a collection
app.post(BASE_API_PATH + "/export-and-import", function(request, response) {
var newStats = request.body;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!newStats) {
console.log("WARNING: New POST request to /export-and-import without stats, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New POST request to /export-and-import with body: " + JSON.stringify(newStats, 2, null));
if (!newStats.province || !newStats.year || !newStats.oil || !newStats.importS || !newStats.exportS) {
console.log("WARNING: The stat " + JSON.stringify(newStats, 2, null) + " is not well-formed, sending 422...");
response.sendStatus(422); // unprocessable entity
}
else {
dbAlberto.find({
province: newStats.province,
year: newStats.year
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
var sExportBefore = sExport.filter((result) => {
return (result.province.localeCompare(newStats.province, "en", {
'sensitivity': 'base'
}) === 0);
});
if (sExportBefore.length > 0) {
console.log("WARNING: The contact " + JSON.stringify(newStats, 2, null) + " already extis, sending 409...");
response.sendStatus(409); // conflict
}
else {
console.log("INFO: Adding contact " + JSON.stringify(newStats, 2, null));
dbAlberto.insert(newStats);
response.sendStatus(201); // created
}
}
});
}
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//POST over a single resource
app.post(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("WARNING: New POST request to /export-and-import-stats/" + province + " and " + year + ", sending 405...");
response.sendStatus(405); // method not allowed
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//PUT over a collection
app.put(BASE_API_PATH + "/export-and-import", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("WARNING: New PUT request to /export-and-import-stats, sending 405...");
response.sendStatus(405); // method not allowed
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//PUT over a single resource
app.put(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var updateExp = request.body;
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!updateExp) {
console.log("WARNING: New PUT request to /export-and-import-stats/ without contact, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New PUT request to /export-and-import-stats/" + province + " with data " + JSON.stringify(updateExp, 2, null));
if (!updateExp.province || !updateExp.year || !updateExp.oil || !updateExp.importS || !updateExp.exportS || updateExp.province !== province || updateExp.year !== year) {
console.log("WARNING: The contact " + JSON.stringify(updateExp, 2, null) + " is not well-formed, sending 422...");
response.sendStatus(422); // unprocessable entity
}
else {
dbAlberto.find({
province: province,
$and: [{
year: year
}]
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
dbAlberto.update({
province: province,
year: year
}, updateExp);
console.log("INFO: Modifying contact with name " + province + " with data " + JSON.stringify(updateExp, 2, null));
response.send(updateExp); // return the updated contact
}
else {
console.log("WARNING: There are not any stats with provinc " + province);
response.sendStatus(404); // not found
}
}
});
}
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//DELETE over a collection
app.delete(BASE_API_PATH + "/export-and-import", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("INFO: New DELETE request to /export-and-import-stats");
dbAlberto.remove({}, {
multi: true
}, function(err, doc) {
if (err) {
console.error('WARNING: Error removing data from DB');
response.sendStatus(500); // internal server error
}
else {
var n = doc.result.n;
if (n !== 0) {
console.log("INFO: Remove: " + n + " stats, sending 204...");
response.sendStatus(204); // no content
}
else {
console.log("WARNING: There are no contacts to delete");
response.sendStatus(404); // not found
}
}
});
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//DELETE over a single resource
app.delete(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province || !year) {
console.log("WARNING: New DELETE request to /export-and-import-stats/:name without name, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New DELETE request to /export-and-import-stats/" + province + " and " + year);
dbAlberto.remove({
province: province,
year: year
}, {}, function(err, doc) {
if (err) {
console.error('WARNING: Error removing data from DB');
response.sendStatus(500); // internal server error
}
else {
var n = doc.result.n;
if (n !== 0) {
console.log("INFO: The stat with name " + province + " and year " + year + " has been succesfully deleted, sending 204...");
response.sendStatus(204); // no content
}
else {
console.log("WARNING: There are no contacts to delete");
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
}
Thanks in advance !

Related

express-ntlm: how to get additional attribute value in req.ntlm?

In express-ntlm package i have added password attribute but i'm not able to get its value while i provide in private window of chrome. I always getting empty value.
My code is:
/* jshint node:true */
// node.js modules
var url = require('url');
// 3rd-party modules
var _ = require('underscore'),
async = require('async');
// Custom modules
var Cache = require('./Cache'),
NTLM_AD_Proxy = require('./NTLM_AD_Proxy'),
NTLM_No_Proxy = require('./NTLM_No_Proxy'),
utils = require('./utils');
const { Domain } = require('domain');
// Globals
var cache = new Cache();
module.exports = function(options) {
// Overwrite the default options by the user-defined
options = _.extend({
badrequest: function(request, response, next) {
response.sendStatus(400);
},
internalservererror: function(request, response, next) {
response.sendStatus(500);
},
forbidden: function(request, response, next) {
response.sendStatus(403);
},
unauthorized: function(request, response, next) {
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM');
response.end();
},
prefix: '[express-ntlm]',
debug: function() {
},
domaincontroller: null,
getConnectionId(request, response) {
return utils.uuidv4();
}
}, options);
function ntlm_message_type(msg) {
if (msg.toString('utf8', 0, 8) != 'NTLMSSP\0') {
return new Error('Not a valid NTLM message:', msg.toString('hex'));
}
var msg_type = msg.readUInt8(8);
if (!~[1, 2, 3].indexOf(msg_type)) {
return new Error('Incorrect NTLM message Type', msg_type);
}
return msg_type;
}
function parse_ntlm_authenticate(msg) {
var DomainNameLen = msg.readUInt16LE(0x1C),
DomainNameBufferOffset = msg.readUInt32LE(0x20),
DomainName = msg.slice(DomainNameBufferOffset, DomainNameBufferOffset + DomainNameLen),
UserNameLen = msg.readUInt16LE(0x24),
UserNameBufferOffset = msg.readUInt32LE(0x28),
UserName = msg.slice(UserNameBufferOffset, UserNameBufferOffset + UserNameLen),
PasswordLen = msg.readUInt16LE(0x34),
PasswordBufferOffset = msg.readUInt32LE(0x38),
Password = msg.slice(PasswordBufferOffset, PasswordBufferOffset + PasswordLen),
WorkstationLen = msg.readUInt16LE(0x2C),
WorkstationBufferOffset = msg.readUInt32LE(0x30),
Workstation = msg.slice(WorkstationBufferOffset, WorkstationBufferOffset + WorkstationLen);
if (utils.isFlagSet(msg.readUInt8(0x3C), utils.toBinary('00000001'))) {
DomainName = DomainName.toString('utf16le');
UserName = UserName.toString('utf16le');
Password = Password.toString('utf16le');
Workstation = Workstation.toString('utf16le');
} else {
DomainName = DomainName.toString();
UserName = UserName.toString();
Password = Password.toString();
Workstation = Workstation.toString();
}
return [UserName, Password, DomainName, Workstation];
}
function decode_http_authorization_header(auth) {
var ah = auth.split(' ');
if (ah.length === 2) {
if (ah[0] === 'NTLM') {
return ['NTLM', new Buffer(ah[1], 'base64')];
}
}
return false;
}
function connect_to_proxy(type1, callback) {
var domain = options.domain;
var proxy,
ntlm_challenge;
async.eachSeries(!options.domaincontroller ? [ -1 ] : typeof options.domaincontroller === 'string' ? [ options.domaincontroller ] : options.domaincontroller, function(server, eachDomaincontrollerCallback) {
if (!server || ntlm_challenge) return eachDomaincontrollerCallback();
if (server === -1) {
options.debug(options.prefix, 'No domaincontroller was specified, all Authentication messages are valid.');
proxy = new NTLM_No_Proxy();
} else if (!server.indexOf('ldap')) {
var serverurl = url.parse(server),
use_tls = serverurl.protocol === 'ldaps:',
decoded_path = decodeURI(serverurl.path);
options.debug(options.prefix, 'Initiating connection to Active Directory server ' + serverurl.host + ' (domain ' + domain + ') using base DN "' + decoded_path + '".');
proxy = new NTLM_AD_Proxy(serverurl.hostname, serverurl.port, domain, decoded_path, use_tls, options.tlsOptions);
} else {
return eachDomaincontrollerCallback(new Error('Domaincontroller must be an AD and start with ldap://'));
}
proxy.negotiate(type1, function(error, challenge) {
if (error) {
proxy.close();
proxy = null;
options.debug(options.prefix, error);
return eachDomaincontrollerCallback();
}
ntlm_challenge = challenge;
return eachDomaincontrollerCallback();
});
}, function(error) {
if (error) return callback(error);
if (!proxy) {
return callback(new Error('None of the Domain Controllers are available.'));
}
return callback(null, proxy, ntlm_challenge);
});
}
function handle_type1(request, response, next, ntlm_message, callback) {
cache.remove(request.connection.id);
cache.clean();
connect_to_proxy(ntlm_message, function(error, proxy, challenge) {
if (error) return callback(error);
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM ' + challenge.toString('base64'));
response.end();
cache.add(request.connection.id, proxy);
return callback();
});
}
function handle_type3(request, response, next, ntlm_message, callback) {
var proxy = cache.get_proxy(request.connection.id);
var userDomainWorkstation = parse_ntlm_authenticate(ntlm_message),
user = userDomainWorkstation[0],
pass = userDomainWorkstation[1],
domain = userDomainWorkstation[2],
workstation = userDomainWorkstation[3];
if (!domain) {
domain = options.domain;
}
proxy.authenticate(ntlm_message, function(error, result) {
if (error) return callback(error);
var userData = {
DomainName: domain,
UserName: user,
Password: pass,
Workstation: workstation,
Authenticated: false
};
request.ntlm = userData;
response.locals.ntlm = userData;
request.connection.ntlm = userData;
if (!result) {
cache.remove(request.connection.id);
options.debug(options.prefix, 'User ' + domain + '/' + user + ' authentication for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.forbidden(request, response, next);
} else {
userData.Authenticated = true;
return next();
}
});
}
return function(request, response, next) {
if (!request.connection.id) {
request.connection.id = options.getConnectionId(request, response);
}
var auth_headers = request.headers.authorization;
var user = request.connection.ntlm;
if (user && user.Authenticated) {
options.debug(options.prefix, 'Connection already authenticated ' + user.DomainName + '/' + user.UserName);
if (auth_headers) {
if (request.method != 'POST') {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
} else {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
}
if (!auth_headers) {
options.debug(options.prefix, 'No Authorization header present');
return options.unauthorized(request, response, next);
}
var ah_data = decode_http_authorization_header(auth_headers);
if (!ah_data) {
options.debug(options.prefix, 'Error when parsing Authorization header for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.badrequest(request, response, next);
}
var ntlm_version = ntlm_message_type(ah_data[1]);
if (ntlm_version instanceof Error) {
options.debug(options.prefix, ntlm_version.stack);
return options.badrequest(request, response, next);
}
if (ntlm_version === 1) {
return handle_type1(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
if (ntlm_version === 3) {
if (cache.get_proxy(request.connection.id) !== null) {
return handle_type3(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
options.debug(options.prefix, 'Unexpected NTLM message Type 3 in new connection for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.internalservererror(request, response, next);
}
options.debug(options.prefix, 'Type 2 message in client request');
return options.badrequest(request, response, next);
};
};
my response is
{"DomainName":"ijk","UserName":"xyz","Password":"","Workstation":"some","Authenticated":true}

Can I use try catch like this in node.js?

I'm making node server, to show up all elements in specific folder.
and have to stop function when path === seekPath,
can I throw result data and catch it to show all elements?
app.get('/view/:id', function(req, res){
if (req.session.key) {
const rawData = fs.readFileSync(__folderTree + req.params.id + ".json")
const jsonData = JSON.parse(rawData)
const seekPath = __storage + req.params.id + "/" + req.query.path
console.log(seekPath)
try {
seekFolder(jsonData, seekPath)
} catch (result) {
showElements(result)
}
}
else {
res.redirect('/login');
}
})
function seekFolder(jsonData, seekPath) {
jsonData.children.forEach(element => {
if(element.type === 'directory'){
console.log("compare " + element.path + " & " + seekPath)
if(element.path === seekPath){
throw(element.children)
}
else{
seekFolderElements(element, seekPath)
}
}
});
}
function showElements(jsonArrData) {
jsonArrData.forEach(element => {
if(element.type === 'directory'){
console.log("!!"+element.name)
showElements(element)
}
else{
console.log("!!"+element.name)
}
});
}

Form saves data to database and them reloads itself

I have this form in my client.html file
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<link rel="stylesheet" type="text/css" href="/css/client.css">
</head>
<body>
<div class="wrapper">
<div class="chatBox">
<div class="chatBoxHead">Chat with Support</div>
<div class="contentArea" style="display: none">
<div class="formArea">
<div class="title">Please fill out this form</div>
<form class="loginForm" id="loginForm">
<div class="inputContainer">
<label for="name"></label>
<input class="nameInput" type="text" placeholder=" * Name" name="name" id="name" required />
</div>
<div class="inputContainer">
<label for="email"></label>
<input class="emailInput" name="email" id="email" type="email" placeholder=" * Email" required />
</div>
<button class="submit" >Submit</button>
</form>
</div>
<div class="chatArea" style="display: none">
<div class="messages">
<div class="oldMsg"></div>
<div class="newMsg"></div>
</div>
<div class='typing'></div>
<input class="inputMessage" rows="1" placeholder="Type here..."></input>
</div>
</div>
</div>
</div>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="../js/client.js"></script>
</body>
</html>
when I click on the submit button for the login form, it saves the data to the database and then reloads itself as opposed to saving the data and then displaying the chat area for messaging. Here is my client.js file
var $window = $(window);
var socket = io();
var $messages = $('.messages');
var $inputMessage = $('.inputMessage');
var $nameInput = $('.nameInput');
var $emailInput = $('.emailInput');
var $formArea = $('.formArea');
var $contentArea = $('.contentArea');
var $login = $('#loginForm');
var $chatArea = $('.chatArea');
var $typing = $(".typing");
var $oldMsg = $('.oldMsg');
var $newMsg = $('.newMsg');
var typing = false;
var timeout = undefined;
var id = localStorage.getItem("roomID");
var active = sessionStorage.getItem('active');
if (active && id) {
$formArea.hide();
$chatArea.show();
socket.emit('add user', {
isNewUser: false,
roomID: id
});
$contentArea.show();
}
$('.chatBoxHead').click(function() {
$contentArea.slideToggle('slow');
if (id != null && !active) {
socket.emit('add user', {
isNewUser: false,
roomID: id
});
$formArea.hide();
$chatArea.show();
$inputMessage.focus();
sessionStorage.setItem('active', true);
active = true;
}
});
$login.submit(function() {
$chatArea.show();
$formArea.hide();
$inputMessage.focus();
sessionStorage.setItem('active', true);
socket.emit('add user', {
isNewUser: true,
Name: $nameInput.val().trim(),
Email: $emailInput.val().trim()
});
});
$inputMessage.keypress(function(event) {
if (event.which !== 13) {
if (typing === false && $inputMessage.is(":focus")) {
typing = true;
socket.emit("typing", {
isTyping: true,
roomID: id,
person: "Client"
});
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 2000);
}
} else {
sendMessage();
clearTimeout(timeout);
timeoutFunction();
}
})
socket.on('chat message', function(data) {
var sender;
if (data.isAdmin){
sender = "msg_admin"
}
else{
sender = "msg_client"
}
var $messageBodyDiv = $('<div class="' + sender + '">' + data.message + '<span class="timestamp">' +
((data.timestamp).toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
});
function sendMessage() {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
var encodedMessage = $('<div />').text(message).html();
message = encodedMessage;
if (message) {
$inputMessage.val('');
var time = ("" + new Date().getTime());
socket.emit('chat message', {
roomID: "null",
message: message,
timestamp: time
});
var $messageBodyDiv = $('<div class="msg_client">' + message + '<span class="timestamp">' +
(time.toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
}
}
function timeoutFunction() {
typing = false;
socket.emit("typing", {
isTyping: false,
roomID: id,
person: "Client"
});
}
$messages.on("scroll", function() {
if ($messages.scrollTop() == 0)
socket.emit("more messages", {});
})
socket.on('roomID', function(roomID) {
id = roomID;
localStorage.setItem("roomID", roomID);
});
socket.on('typing', function(data) {
if (data.isTyping && data.person != 'Client')
$Typing.append("Support is typing...");
else
$Typing.text('');
});
socket.on('chat history', function(data) {
var len = data.history.length;
for (var i = len - 1; i >= 0; i--)
addMessages(data.history[i], false);
});
socket.on('more chat history', function(data) {
var len = data.history.length;
for (var i = 0; i < len; i++)
addMessages(data.history[i], true);
});
function addMessages(data, getMore) {
var sender;
if (data["who"]){
sender = "msg_admin"
}
else{
sender = "msg_client"
}
var $messageBodyDiv = $('<div class="' + sender + '">' + data["message"] + '<span class="timestamp">' +
(data["timeStamp"]).toLocaleString().substr(15, 6) + '</span></div>');
if (getMore) {
$messageBodyDiv.insertAfter($oldMsg);
$messages[0].scrollTop += $messageBodyDiv.outerHeight();
} else {
$messageBodyDiv.insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
}
}
socket.on('log message', function(text) {
var time = ("" + new Date().getTime());
var $messageDiv = $('<div class="msg_admin">' + text + '<span class="timestamp">' +
(time.toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
});
socket.on('disconnect', function() {
console.log("Disconnected!");
$inputMessage.prop('disabled', true);
$inputMessage.prop('placeholder', "Connection Lost! Reconnecting..");
});
socket.on('reconnect_failed', function() {
console.log("Reconnection Failed!");
$inputMessage.prop('placeholder', "No active connection. Please refresh page.");
});
socket.on('reconnect', function() {
setTimeout(function() {
console.log("Reconnected!");
$inputMessage.prop('disabled', false);
$inputMessage.prop('placeholder', "Type here...");
if (active && id)
socket.emit('add user', {
isNewUser: false,
roomID: id
});
}, 10000);
});
Also here is my app.js file
var express = require('express');
var app = express();
var fs = require('fs');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var uuid = require('uuid');
var config = require(__dirname + "/config.js");
var r = require('rethinkdb');
var _ = require("underscore");
var db = require('./controllers/db');
var btoa = require('btoa');
var users = {};
var admins = {};
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(require("express-session")({
secret: "luxtag chat",
resave: false,
saveUninitialized: false
}));
// Setup rethinkDB database
db.setupDB();
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/client.html');
});
app.get(config.rethinkdb.admin_url, function(req, res) {
res.sendFile(__dirname + '/views/admin.html');
});
io.on('connection', function(socket){
console.log(`Socket ID: ${socket.id}`);
console.dir(socket.handshake, {colors: true});
//Admin login
socket.on('login', function(data) {
if (btoa(data.password) != config.rethinkdb.key)
socket.emit('login', {
login: false,
err: "Invalid Login"
})
else {
if (_.find(config.rethinkdb.admin_users, function(admin) {
return (admin == data.admin);
})) {
if (admins[data.admin]) {
socket.emit('login', {
login: false,
err: "Already Logged In"
})
} else {
socket.emit('login', {
login: true
})
}
} else {
socket.emit('login', {
login: false,
err: "Invalid Login"
})
}
}
});
socket.on('add admin', function(data) {
this.isAdmin = data.isAdmin;
socket.username = data.admin;
console.log('admins: ', admins);
console.log('users: ', users);
_.each(admins, function(adminSocket) {
adminSocket.emit("admin added", socket.username)
socket.emit("admin added", adminSocket.username)
});
admins[socket.username] = socket;
//If some user is already online on chat
if (Object.keys(users).length > 0) {
_.each(users, function(userSocket) {
db.getMessages(userSocket.roomID, 0)
.then(function(history) {
var len = history.length;
var userSocket = users[history[len - 1]];
history.splice(-1, 1);
socket.join(userSocket.roomID);
socket.emit("New Client", {
roomID: userSocket.roomID,
history: history,
details: userSocket.userDetails,
justJoined: true
})
})
});
}
});
socket.on('add user', function(data) {
socket.isAdmin = false;
if (data.isNewUser) {
data.roomID = uuid.v4();
var user = {
id: data.roomID,
name: data.Name,
email: data.Email
}
console.log(user);
db.saveUser(user, function (saved, err) {
if (saved) {
console.log('user saved...');
return;
}
if (err) {
console.log('There was an error creating the account');
}
else {
console.log("The account wasn't created");
}
});
socket.emit("roomID", data.roomID);
}
socket.roomID = data.roomID;
console.log('socket.roomID: ', socket.roomID);
//get user
db.findUserById(socket.roomID, function(err, details) {
if(err){
console.log("Line 60 : ", error);
}
else {
socket.userDetails = details;
console.log('socket.userDetails: ', socket.userDetails);
}
});
socket.join(socket.roomID);
var newUser = false;
if (!users[socket.roomID]) {
users[socket.roomID] = socket;
newUser = true;
}
//get message history
db.getMessages(socket.roomID, 0)
.then(function(history) {
history.splice(-1, 1)
socket.emit('chat history', {
history: history,
getMore: false
});
if (Object.keys(admins).length == 0) {
//Tell user he will be contacted asap
socket.emit('log message', "Thank you for reaching us." +
" Please leave your message here and we will get back to you shortly.");
} else {
if (newUser) {
socket.emit('log message', "Hello " + socket.userDetails['name'] + ", How can I help you?");
//Make all available admins join this users room.
_.each(admins, function(adminSocket) {
adminSocket.join(socket.roomID);
adminSocket.emit("New Client", {
roomID: socket.roomID,
history: history,
details: socket.userDetails,
justJoined: false
})
});
}
}
})
.catch(function(error) {
console.log("Line 113 : ", error)
})
.done();
db.getMsgLength(socket.roomID)
.then(function(len) {
socket.MsgHistoryLen = (len * -1) + 10;
socket.TotalMsgLen = (len * -1);
})
.catch(function(error) {
console.log("Line 121 : ", error)
})
.done();
});
socket.on('chat message', function(data){
if (data.roomID === "null"){
data.roomID = socket.roomID;
}
data.isAdmin = socket.isAdmin;
var msg = {
who: data.isAdmin,
message: data.message,
timestamp: data.timestamp
}
db.saveMessage(msg, function (err, saved) {
if (err || !saved) {
console.log('There was an error saving your message');
return;
}
socket.broadcast.to(data.roomID).emit('chat message', data);
});
});
socket.on("typing", function(data) {
socket.broadcast.to(data.roomID).emit("typing", {
isTyping: data.isTyping,
person: data.person,
roomID: data.roomID
});
});
socket.on("more messages", function() {
if (socket.MsgHistoryLen < 0) {
db.getMessages(socket.roomID, socket.MsgHistoryLen)
.then(function(history) {
history.splice(-1, 1)
socket.emit('more chat history', {
history: history
});
})
socket.MsgHistoryLen += 10;
}
});
socket.on('disconnect', function() {
if (socket.isAdmin) {
delete admins[socket.username];
_.each(admins, function(adminSocket) {
adminSocket.emit("admin removed", socket.username)
});
} else {
if (io.sockets.adapter.rooms[socket.roomID]) {
var total = io.sockets.adapter.rooms[socket.roomID]["length"];
var totAdmins = Object.keys(admins).length;
var clients = total - totAdmins;
if (clients == 0) {
//check if user reconnects in 10 seconds
setTimeout(function() {
if (io.sockets.adapter.rooms[socket.roomID]){
total = io.sockets.adapter.rooms[socket.roomID]["length"];
}
totAdmins = Object.keys(admins).length;
if (total <= totAdmins) {
delete users[socket.roomID];
socket.broadcast.to(socket.roomID).emit("User Disconnected", socket.roomID);
_.each(admins, function(adminSocket) {
adminSocket.leave(socket.roomID)
});
}
}, 10000);
}
} else {
if (socket.userDetails)
delete users[socket.roomID];
}
}
});
});
http.listen(config.express.port, function(){
console.log('listening on *:' + config.express.port);
});
any help would be greatly appreciated.
Setup a submit function in your js that does the POST request to the server and prevent the default behavior. jQuery example:
$( "#target" ).submit(function( event ) {
event.preventDefault();
// Do post request here
});
I supposing, you get a success promise after data stored in database successfully.
You need to prevent automatic form submission. Look out below code.
<!DOCTYPE html>
<html>
<body>
<form onsubmit="return toSubmit();">
First name:<br>
<input id="name" type="text" name="firstname" >
<br>
Last name:<br>
<input type="text" name="lastname" >
<br><br>
<button type="submit" >Submit</button>
</form>
<script>
function toSubmit(){
if(document.getElementById('name').value == "tushar"){
alert("success");
return true;
}
else{
alert("failed");
return false;
}
}
</script>
</body>
</html>

JSON.parse unexpected end of input error in NodeJS MailParser

I am executing a code in NodeJS child_process.
I used MailParser of Andris9.
I used console.log(JSON.stringify({obj:mail_object})); to get the data of mail_object to the parent.
In the parent, I have this code, JSON.parse(retVal);.
The error came up is "Unexpected end of Input".
This error only shows when the email I received is having an attachment.
If the email doesnt have attachment, there is no error.
Here is the parent method,
getEmails(){
let workerProcess = child_process.spawn('node', [basePath+'imports/workers/retrieveEmail.js']);
workerProcess.stdout.on('data', function (data) {
try{
let retVal = new Buffer(data).toString();
retVal = JSON.parse(retVal);
console.log(retVal);
if(typeof retVal.err == "undefined"){
console.log(retVal.obj.from[0].address);
Fiber(function () {
var objs = [];
if (typeof retVal.obj.attachments !== "undefined") {
console.log("Test passed");
retVal.obj.attachments.forEach(function (attachment) {
let future = new Future();
Fiber(function () {
Files.write(attachment.content, {
fileName: attachment.fileName,
type: attachment.contentType
}, function (error, fileRef) {
if (error) {
future.throw(new Meteor.Error(500, error.message));
} else {
...
}
});
}).run();
var bool = true;
if (bool = future.wait())
objs.push(bool);
});
}
...
}).run();
}else{
console.log(retVal.err);
}
}catch(e){
console.log(e);
}
});
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
workerProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
},
I removed some unnecessary codes.
Here is my retrieveEmail.js,
...
client.on("retr", function (status, msgnumber, data, rawdata) {
if (status === true) {
var mailparser = new MailParser({
streamAttachments: false
});
var timeStamp = Math.floor(Date.now());
mailparser.on("attachment", function (attachment, mail) {
console.log(JSON.stringify({err:"testpassed1"}));
});
mailparser.on("end", function (mail_object) {
console.log(JSON.stringify({err:"testpassed2"}));
console.log(JSON.stringify({obj:mail_object}));
});
mailparser.write(data);
mailparser.end();
client.dele(msgnumber);
} else {
console.log("RETR failed for msgnumber " + msgnumber);
client.quit();
}
});
...

TypeError: Cannot read property 'length' of undefined and other errors

Whenever I try to run the JS code with node in CMD I get this error:
Oh and the bot probably cannot be run since stackoverflow needs permission from mySQL database.
TypeError: Cannot read property 'length' of undefined
at Query._callback (C:\Users\George\Desktop\bot2\websitebot.js:138:9)
at Query.Sequence.end (C:\Users\George\node_modules\mysql\lib\protocol\sequences\Sequence.js:86:24)
at Query.ErrorPacket (C:\Users\George\node_modules\mysql\lib\protocol\sequences\Query.js:94:8)
at Protocol._parsePacket (C:\Users\George\node_modules\mysql\lib\protocol\Protocol.js:280:23)
at Parser.write (C:\Users\George\node_modules\mysql\lib\protocol\Parser.js:74:12)
at Protocol.write (C:\Users\George\node_modules\mysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (C:\Users\George\node_modules\mysql\lib\Connection.js:109:28)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
This is the code I'm trying to run, I honestly have no idea why I am getting these errors. Incase someone here might help me:
//The required liberys for the bot to work
var Steam = require('steam')
var SteamUser = require('steam-user');
var SteamTotp = require('steam-totp');
var SteamConfirm = require('steamcommunity-mobile-confirmations');
var SteamTradeOffers = require('steam-tradeoffers');
var TradeOfferManager = require('steam-tradeoffer-manager');
var TOTP = require('onceler').TOTP;
var request = require('request');
var mysql = require('mysql');
var offers = new SteamTradeOffers();
var apik = 'xxx'; //The API Key of the bot.
var botsteamid = 'xxx'; //The SteamID of the bot.
var identitysecret = 'xxx'; //The identity secret of the bot.
var sharedsecret = 'xxx'; //The shared secret of the bot
var botusername = 'xxx';
var botpassword = 'xxx';
var admin = 'xxx'; //The steamid of the Admin.
var botid = 'xxx'; //The ID of the bot..
var pooling_interval = 10000; // 10 seconds by default, the bot checks for outgoing confirmations every X seconds, defined here
//Setting up device identity
var deviceid=SteamTotp.getDeviceID(botsteamid);
//Making the bot log in.
var details = {
"accountName" : botusername, // Bot username
"password" : botpassword, // Bot password
"twoFactorCode" : SteamTotp.generateAuthCode(sharedsecret)
};
var client = new SteamUser();
var manager = new TradeOfferManager({
"steam" : client,
"domain" : "localhost", //localhost
"language" : "en",
})
//Setting up the MySQL Connection - This is where I have errors.
var connection = mysql.createConnection({
host : 'xxx', // MYSQL , LEAVE IT AS LOCALHOST IF YOU RUN IT ON THE SAME SERVER AS THE WEBSITE AND DATABASE
user : 'xxx', // MYSQL USERNAME
password : 'xxx', // MYSQL PASSWORD
database : 'xxx', // MYSQL DATABASENAME
charset : 'utf8_general_ci'
});
connection.connect();
client.logOn(details);
//Checking mobile confirmations
function checkConfirmations(steamcommunityMobileConfirmations){
steamcommunityMobileConfirmations.FetchConfirmations((function (err, confirmations)
{
if (err)
{
console.log('Confirmations error: '+err);
if(err=='Error: 503') // This is an error you can most likely ignore, except if it's spammed a lot - To fix it simply restart the bot
{
}
if(err=='Error: Invalid protocol: steammobile:') // - To fix it simply restart the bot
{
// A fix should be coming soon!
}
return;
}
if(confirmations.length>0)
{
console.log('[SERVER] Received ' + confirmations.length + ' confirmations');
}
if ( ! confirmations.length)
{
return;
}
steamcommunityMobileConfirmations.AcceptConfirmation(confirmations[0], (function (err, result)
{
if (err)
{
console.log(err);
return;
}
console.log('[SERVER] Confirmation handling result: ' + result);
}).bind(this));
}).bind(this));
}
//Done with the functions, time to do commands.
//Logging the bot in
client.on('loggedOn', function(details)
{
client.on('webSession', function(sessionID, cookies){
manager.setCookies(cookies, function(err) {
if(err) {
console.log('setCookies error: '+err);
process.exit(1); // Fatal error since we couldn't get our API key
return;
}
var steamapi=manager.apiKey;
var SteamcommunityMobileConfirmations = require('steamcommunity-mobile-confirmations');
var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
{
steamid: botsteamid,
identity_secret: identitysecret,
device_id: deviceid,
webCookie: cookies,
});
setInterval(function(){
checkConfirmations(steamcommunityMobileConfirmations)
}, pooling_interval);
console.log("[SERVER] The Bot has logged in!");
client.addFriend(admin);
client.setPersona(Steam.EPersonaState.LookingToTrade);
});
offers.setup({
sessionID: sessionID,
webCookie: cookies,
APIKey: apik
});
});
});
function checkWithdraw(){
connection.query("SELECT * FROM `withdraw` WHERE active=1 AND `botid`='"+botid+"' AND tradestatus='Queued' LIMIT 1", function(err, row, fields) {
if (!row.length) {
return;
}
var tradeid = row[0].id;
var sendItems = (row[0].assetids).split(',');
var item=[],num = 0;
for (i = 0; i < sendItems.length; i++) {
item[num] = {
appid: 730,
contextid: 2,
amount: 1,
assetid: sendItems[i]
}
num++;
}
offers.makeOffer ({
partnerSteamId: row[0].steamid,
accessToken: row[0].token,
itemsFromMe: item,
itemsFromThem: [],
message: 'Withdraw from '
},
function(err, response) {
if (err) {
console.log(err);
return;
}
console.log('Tradeoffer sent to ' + row[0].steamid);
tradeofferquery = response;
tradeofferid = (tradeofferquery['tradeofferid']);
connection.query('UPDATE `withdraw` SET `tradeid`=\''+tradeofferid+'\', `tradestatus`="Sent" WHERE `id`=\''+tradeid+'\'', function(err, row, fields) {});
})
});
}
function checkDeposit(){
connection.query("SELECT * FROM `deposits` WHERE `credited`=\'0\' AND `tradestatus`=\'Queued\' AND `botid`='"+botid+"' LIMIT 1", function(err, row, fields) {
if (!row.length) {
return
}
offers.getHoldDuration({partnerSteamId: row[0].steamid, accessToken: row[0].token}, function(err, response)
{
if (err)
{
return;
}
escrowduration = response;
thesd = (escrowduration['their']);
if(thesd === 0){
var tradeid = row[0].id;
var sendItems = (row[0].assetids).split(',');
var item=[],num = 0;
for (i = 0; i < sendItems.length; i++) {
item[num] = {
appid: 730,
contextid: 2,
amount: 1,
assetid: sendItems[i]
}
num++;
}
console.log(item);
offers.makeOffer ({
partnerSteamId: row[0].steamid,
accessToken: row[0].token,
itemsFromMe: [],
itemsFromThem: item,
message: 'Deposit to , code: ' + row[0].code
}, function(err, response) {
if (err) {
console.log(err);
return;
}
console.log('Tradeoffer sent to ' + row[0].steamid);
tradeofferquery = response;
tradeofferid = (tradeofferquery['tradeofferid']);
connection.query('UPDATE `deposits` SET `tradeid`=\''+tradeofferid+'\', `tradestatus`="Sent" WHERE `id`=\''+tradeid+'\'', function(err, row, fields) {});
})
} else {
connection.query('DELETE FROM `deposits` WHERE `steamid`=\''+ row[0].steamid +'\'', function(err, row, fields) {});
console.log('They are in escrow');
}
});
});
}
//Keeping track of sent offers.
manager.on('sentOfferChanged', function(offer, oldState) {
console.log("Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));
connection.query('UPDATE `deposits` SET `tradestatus`=\''+TradeOfferManager.getStateName(offer.state)+'\' WHERE `tradeid`=\''+offer.id+'\'');
connection.query('UPDATE `withdraw` SET `tradestatus`=\''+TradeOfferManager.getStateName(offer.state)+'\' WHERE `tradeid`=\''+offer.id+'\'');
if(offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
offer.getReceivedItems(function(err, items) {
if(err) {
console.log("Couldn't get received items: " + err);
} else {
items.forEach(function(item)
{
console.log('Recieved: ' + item.name);
connection.query('INSERT INTO `bank` (`botid`,`assetid`,`img`,`name`,`status`) VALUES (\''+botid+'\',\''+item.assetid+'\',\''+item.icon_url+'\',\''+item.market_name+'\',\'1\')', function(err, row, fields) {});
})
}
});
}
if(offer.state != (TradeOfferManager.ETradeOfferState.Accepted || TradeOfferManager.ETradeOfferState.Active)) {
connection.query('DELETE FROM `deposits` WHERE `tradeid`=\''+offer.id+'\'');
connection.query('DELETE FROM `withdraw` WHERE `tradeid`=\''+offer.id+'\'');
}
});
//Processing incomming offers
manager.on('newOffer', function(offer)
{
offer.decline(function(err)
{
console.log('[DEBUG] Declined Counter offer.');
if (err)
{
console.log('Decline error: '+err);
}
connection.query('DELETE FROM `deposits` WHERE `tradeid`=\''+offer.id+'\'');
connection.query('DELETE FROM `withdraw` WHERE `tradeid`=\''+offer.id+'\'');
});
});
setInterval(function() {
checkDeposit();
checkWithdraw();
}, 5000);
//Numeric and float
function is_float(mixed_var)
{
return +mixed_var === mixed_var && (!isFinite(mixed_var) || !! (mixed_var % 1));
}
function isNumeric(n){
return (typeof n == "number" && !isNaN(n));
}
//Setting up chat commands for the admin
client.on('friendMessage#'+admin+'', function(steamID, message)
{
console.log("[SERVER] Admin to Bot: " + message);
if((message.indexOf("ping") == 0) || (message.indexOf("/cmd") == 0))
{
checkDeposit();
client.chatMessage(admin, 'Pong!');
}
if((message.indexOf("pong") == 0) || (message.indexOf("/cmd") == 0))
{
checkWithdraw();
client.chatMessage(admin, 'Pong!');
}
if(message.indexOf("/code") == 0)
{
var code = SteamTotp.generateAuthCode(sharedsecret);
client.chatMessage(admin, '[SERVER] Your login code: '+code+'');
}
});
If i understod your question right this is where the error occur.
connection.query("SELECT * FROM `withdraw` WHERE active=1 AND `botid`='"+botid+"' AND tradestatus='Queued' LIMIT 1", function(err, row, fields) {
if (!row.length) {
return;
}
Im kind of new too the mysql area but i whould try to write the code something like this instead:
connection.query("SELECT * FROM `withdraw` WHERE active=1 AND `botid`= ? AND tradestatus='Queued' LIMIT 1",botid , function(err, rows, fields) {
if (!rows.length) {
return;
}
What ive done is changed the place where you input the "botid" to a "?" instead, that takes the value from the botid right before your function, and row is now rows just for code clearance.
As you said, i cant access your DB but i hope that this might work. Let me know!

Categories