NodeJs, if statements inside connection.query - javascript

i am a c# guy trying to create a login page using in react, node and mysql. i have a doubt that can i write 'if statements inside connection.query'. Below is the code snippet i am using. When i am trying to run this script, i am getting proxy error.
app.post('/api/world', (req, res) => {
try{
console.log(req.body);
uname = req.body.post;
var DBuserCheck = "SELECT EXISTS (SELECT * FROM `loginschema`.credentials WHERE uname =" + '"' + uname + '"' + ")";
var DBpwdCheck = "SELECT pwd FROM `loginschema`.credentials WHERE uname =" + '"' + uname + '"';
connection.query(DBuserCheck, function(err,data){
if(DBuserCheck){
connection.query(DBpwdCheck, function(err, pdata){
if(pdata == req.body.password){
res.json({Successfully_loggedin});
}
(err)? res.send(err) : res.json({pwdData_Wrong_Password: pdata});
console.log('enter valid credentials');
});
}
(err) ? res.send(err) : res.json({ USERdata: data });
console.log('user query data: dataSTR',+data +" ; req string "+ req.body.post +"; uname string "+ uname);
});
}
catch(ex){
console.log('Message from Catch is ----->>>> '+ex);
}
});
Is my code correct or i have to follow any other procedure. My code first runs correctly and crashes at the ending. I am getting the below error.
PS H:\PyProjects\login\loginproj> yarn dev
yarn run v1.17.3
$ concurrently --kill-others-on-fail "yarn server" "yarn client"
$ cd client && yarn start
$ nodemon server.js
$ react-scripts start
[0] [nodemon] 1.19.4
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching dir(s): *.*
[0] [nodemon] watching extensions: js,mjs,json
[0] [nodemon] starting `node server.js`
[0] Listening on port 5000
[1] Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade caniuse-lite browserslist`
[1] Starting the development server...
[1]
[1] Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`
[1] Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`
[1] Compiled successfully!
[1]
[1] You can now view create-react-app-express in the browser.
[1]
[1] Local: http://localhost:3000/
[1] On Your Network: http://10.0.0.65:3000/
[1]
[1] Note that the development build is not optimized.
[1] To create a production build, use yarn build.
[1]
[0] {}
[0] user query data: dataSTR NaN ; req string undefined; uname string undefined
[0] H:\PyProjects\login\loginproj\node_modules\mysql\lib\protocol\Parser.js:437
[0] throw err; // Rethrow non-MySQL errors
[0] ^
[0]
[0] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0] at ServerResponse.setHeader (_http_outgoing.js:470:11)
[0] at ServerResponse.header (H:\PyProjects\login\loginproj\node_modules\express\lib\response.js:771:10)
[0] at ServerResponse.send (H:\PyProjects\login\loginproj\node_modules\express\lib\response.js:170:12)
[0] at ServerResponse.json (H:\PyProjects\login\loginproj\node_modules\express\lib\response.js:267:15)
[0] at Query.<anonymous> (H:\PyProjects\login\loginproj\server.js:44:36)
[0] at Query.<anonymous> (H:\PyProjects\login\loginproj\node_modules\mysql\lib\Connection.js:525:10)
[0] at Query._callback (H:\PyProjects\login\loginproj\node_modules\mysql\lib\Connection.js:491:16)
at Query.Sequence.end (H:\PyProjects\login\loginproj\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
[0] at Query._handleFinalResultPacket (H:\PyProjects\login\loginproj\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
[0] at Query.EofPacket (H:\PyProjects\login\loginproj\node_modules\mysql\lib\protocol\sequences\Query.js:123:8)
[0] [nodemon] app crashed - waiting for file changes before starting...
[1] Proxy error: Could not proxy request /api/world from localhost:3000 to http://localhost:5000/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

Accoding to your error from your code send response multiple times, so here is your working code
app.post('/api/world', (req, res) => {
try {
console.log(req.body);
uname = req.body.post;
var DBuserCheck = "SELECT EXISTS (SELECT * FROM `loginschema`.credentials WHERE uname =" + '"' + uname + '"' + ")";
var DBpwdCheck = "SELECT pwd FROM `loginschema`.credentials WHERE uname =" + '"' + uname + '"';
connection.query(DBuserCheck, function (err, data) {
if(err) {
res.send(err) : res.json({ USERdata: data })
console.log('user query data: dataSTR', +data + " ; req string " + req.body.post + "; uname string " + uname);
} else {
connection.query(DBpwdCheck, function (err, pdata) {
if (pdata == req.body.password) {
res.json({ Successfully_loggedin });
} else {
(err) ? res.send(err) : res.json({ pwdData_Wrong_Password: pdata });
console.log('enter valid credentials');
}
});
}
});
}
catch (ex) {
console.log('Message from Catch is ----->>>> ' + ex);
}
});

This solved my issue. I added if statement like this .
if(loginUserId ===stat.userId && singlePost.id){
return Object.assign({}, {
stat_id: stat.id,
is_status : true,
})
} else if(loginUserId ===userId){
return Object.assign({}, {
stat_id: stat.id,
is_status : true,
})
} else {
return Object.assign({}, {
stat_id: stat.id,
is_status : false,
})
}

Related

I want to first connect to aws and hit a python command from Nodejs via Api. Not sure how to do?

I want to execute 'python3 sample.py --path.data=/root/tej4' command from nodejs.The below is my code -
const runningPython = async(req,res,next) => {
ssh.connect({
host: '******',
port: 22,
username: 'ubuntu',
privateKey: '*******'
}).then(function () {
exec('python3 sample.py --path.data=/root/tej4', (err, stdout, stderr) => {
if (err) {
console.log(err)
}
// the *entire* stdout and stderr (buffered)
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
})
}
But what I am getting response is its trying to run locally rather than on aws cli. Not sure how to achieve this?
Error: Command failed: python3 sample.py --path.data=/root/tej4
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
at ChildProcess.exithandler (node:child_process:397:12)
at ChildProcess.emit (node:events:390:28)
at maybeClose (node:internal/child_process:1064:16)
at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5) {
killed: false,
code: 9009,
signal: null,
cmd: 'python3 sample.py --path.data=/root/tej4'
}
stdout:
stderr: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
You have to create an instance of type node_ssh and use that instance to call connect and executeCommand methods
const node_ssh = require('node-ssh');
const ssh = new node_ssh();
ssh
.connect({
host: '******',
port: 22,
username: 'ubuntu',
privateKey: '*******'
})
.then(() => {
ssh.execCommand('python3 sample.py --path.data=/root/tej4', { cwd:'/your-python-script-path-here' })
.then((result) => {
console.log('STDOUT: ' + result.stdout)
console.log('STDERR: ' + result.stderr)
});
You can use ssh lib, but for sudo su and running multiple commands switch to ssh2shell, the code for that is mentioned below:
const runningPython = async (req, res, next) => {
var host = {
server: {
host: ***** ,
username: ***** ,
privateKey: fs.readFileSync('ppk file path'),
},
commands: ["sudo su -", "python3 sample.py --path.data=root/tej4"],
onCommandComplete: function (command, response, sshObj) {
if (sshObj.debug) {
this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete event, command: " + command);
}
if (command === "sudo su -" && response.indexOf("/root") != -1) {
sshObj.commands.unshift("msg:The command and response check worked. Added another cd command.");
sshObj.commands.unshift("cd .ssh");
} else if (command === "python3 sample.py --path.data=root/tej4") {
this.emit("msg", response);
}
},
onEnd: function (sessionText, sshObj) {
if (sshObj.debug) {
this.emit("msg", this.sshObj.server.host + ": host.onEnd event");
}
}
};
let SSH = new SSH2Shell(host),
//Use a callback function to process the full session text
callback = function (sessionText) {
console.log(sessionText)
}
//Start the process
SSH.connect(callback);
}

NodeJS rmdir function error on LINUX ONLY?

So I'm running this section of my NodeJS script on my Windows 10 device running the latest version of Node and another version on my webserver running CentOS8 Linux. When this code is run on windows, it outputs what I would expect but when I run it on my Linux machine, it errors on this line:
fs.rmdir('public/u/' + info[0] + '/', { recursive: true }, (err) => {
With this error:
fs.js:136
throw new ERR_INVALID_CALLBACK();
^
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
at makeCallback (fs.js:136:11)
at Object.rmdir (fs.js:671:14)
at /home/frontlinemist57server/celeste.js:156:8
at /home/frontlinemist57server/node_modules/line-reader/lib/line_reader.js:279:15
at getLine (/home/frontlinemist57server/node_modules/line-reader/lib/line_reader.js:166:7)
at Object.nextLine (/home/frontlinemist57server/node_modules/line-reader/lib/line_reader.js:183:7)
at Immediate.readNext (/home/frontlinemist57server/node_modules/line-reader/lib/line_reader.js:269:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
Any ideas?
app.post('/api/purge', (req, res) => {
// Get Sent Token //
var giventoken = req.body.token;
var authed = false;
lineReader.eachLine('accounts.txt', function(line, last) {
// If Valid Token //
if (crypto.createHash('md5').update(line).digest("hex") == giventoken) {
authed = true;
var info = line.split("§");
if (fs.existsSync('public/u/' + info[0] + '/')){
fs.rmdir('public/u/' + info[0] + '/', { recursive: true }, (err) => {
if (err) {
res.send(err);
throw err;
} else {
console.log("Account Purged: " + info[0]);
res.send('purged');
}
}
)}
// If Invalid Token //
} else if (last) {
if (authed == false) {
console.log("Invalid Purge Token: " + giventoken);
res.write("invalid");
res.end();
}
}
});
});
Edit: Both Windows and Linux systems are running the same version of node.
It turns out that DNF doesn't actually update you to the latest version of node for some reason. The server was still running an out of date version of node.
This is how I fixed it:
sudo dnf rm nodejs
curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash -
sudo dnf install nodejs

Why my RestFul API with express and nodejs crashed everyday?

I have restful api with express and nodejs but this api crashed every time.
So.. I have one function for datatime. This function will replace date in the url address everytime to current datetime.. Im not sure but may be when the current date is change with the new current date the API crashed..
I see this error message on the console:
events.js:187
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:201:27)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\Connection.js:426:8)
at Protocol.emit (events.js:210:5)
at Protocol._delegateError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.handleNetworkError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\protocol\Protocol.js:371:10)
at Connection._handleNetworkError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\Connection.js:421:18)
at Socket.emit (events.js:210:5)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! express-api#1.0.0 start: `node server.js`
npm ERR!
npm ERR! Failed at the express-api#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2019-12-29T04_48_17_190Z-debug.log
So this is the code for api.. Its very simple.. but I dont know how to fix this error.
When I wake up and try to see the data from the API every time the API is crashed.
This is the code from the api:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 8000
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});
var con = mysql.createConnection({
host: "192.168.0.1",
port: "1234",
user: "username",
password: "password"
});
let aladinModel = '';
let aladinModelStations = '';
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
var dateNow = formatDate(Date());
app.route('/')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
const date = req.query.date;
const id = req.query.id;
const daysForward = req.query.daysForward;
try {
const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram_cell('${dateNow}', ${id}, ${daysForward})`;
con.query(query, function (err, result, fields) {
if (err) throw err;
aladinModel = result;
});
res.json({ aladinModel })
} catch (error) {
console.log("Error query database!!!");
}
});
app.route('/stations')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
try {
const query2 = `SELECT Station,Ime FROM aladin_surfex.stations_cells;`;
con.query(query2, function (err, result2, fields) {
if (err) throw err;
aladinModelStations = result2;
});
res.json({ aladinModelStations })
} catch (error) {
console.log("Error query database!!!");
}
});
app.use(function (req, res) {
res.status(404);
});
I try to remove the cashe, to update npm, to restart the computer. But without the result.
With nodemon crashed the same..
What can I do ? How can to fix that ?
The error seems to be related to the connection to mysql.
As mysqljs documentation (https://github.com/mysqljs/mysql#error-handling):
Note: 'error' events are special in node. If they occur without an attached listener, a stack trace is printed and your process is killed.
You shuld intercept the connection error like this:
connection.on('error', function(err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
so you can investigate when and why the error occours and eventually you can recreate the connection when a problem occurs.
Move app.listen to the bottom of the file, after you declare all the routes and connect to the database.
Use app.get('route', function...) (more on that in the Express docs)
Move res.json() inside the callback function for each database query. The result will come back asynchronously so will not be accessible outside the function. If you’re new to async and callbacks in Javascript I’d recommend googling them and you’ll find a ton of reading materials.
Initialize your variables, e.g const aladinModel = ...

Node.js upload error to Heroku, Web process failed to bind to $PORT within 60 seconds of launch

I am trying to upload a basic node.js server application to heroku. In localhost it works very well. However, when I upload it to the Heroku the application does not work somehow. Here is my code and my logs. Thank you very much.
var DEFAULT_PORT = process.env.PORT || 8080;
var DEFAULT_HOST = '127.0.0.1'
var SERVER_NAME = 'healthrecords'
var getRequestCounter = 0;
var postRequestCounter = 0;
var putRequestCounter = 0;
var deleteRequestCounter = 0;
var patientArray = [];
var http = require ('http');
var mongoose = require ("mongoose");
var port = process.env.PORT;
var ipaddress = process.env.IP; // TODO: figure out which IP to use for the heroku
// Here we find an appropriate database to connect to, defaulting to
// localhost if we don't find one.
var uristring =
process.env.MONGODB_URI ||
'mongodb://tekstil:teksdev07#ds151753.mlab.com:51753/mapd713groupproject';
//'mongodb://localhost/e-health-db';
// Makes connection asynchronously. Mongoose will queue up database
// operations and release them when the connection is complete.
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Successfully connected to: ' + uristring);
}
});
// This is the schema. Note the types, validation and trim
// statements. They enforce useful constraints on the data.
var patientSchema = new mongoose.Schema({
first_name: String,
last_name: String,
blood_gorup: String,
address: String,
date_of_birth: String,
date_admitted: String,
department: String,
doctor: String,
ailment:String,
});
// Compiles the schema into a model, opening (or creating, if
// nonexistent) the 'Patients' collection in the MongoDB database
var Patient = mongoose.model('Patient', patientSchema);
var restify = require('restify')
// Create the restify server
, server = restify.createServer({ name: SERVER_NAME})
if (typeof ipaddress === "undefined") {
// Log errors on OpenShift but continue w/ 127.0.0.1 - this
// allows us to run/test the app locally.
console.warn('No process.env.IP var, using default: ' + DEFAULT_HOST);
ipaddress = DEFAULT_HOST;
};
if (typeof port === "undefined") {
console.warn('No process.env.PORT var, using default port: ' + DEFAULT_PORT);
port = DEFAULT_PORT;
};
server.listen(port, ipaddress, function () {
console.log('Server %s listening at %s', server.name, server.url)
console.log('Resources:')
console.log(' /patients')
console.log(' /patients/:id')
})
server
// Allow the use of POST
.use(restify.plugins.fullResponse())
// Maps req.body to req.params so there is no switching between them
.use(restify.plugins.bodyParser())
// Get all patients in the system
server.get('/patients', function (req, res, next) {
getRequestCounter++;
console.log('received GET request.');
console.log("Processed Request Counter --> GET: " + getRequestCounter + ", POST: " + postRequestCounter + ", PUT: " + putRequestCounter +", DELETE: " +deleteRequestCounter);
// Find every entity within the given collection
Patient.find({}, function (error, patients) {
// Return all of the patients in the system
res.send(patients)
console.log('Sending response to GET request.');
})
})
// Get a single patient by its patient id
server.get('/patients/:id', function (req, res, next) {
getRequestCounter++;
console.log('received GET request.');
console.log("Processed Request Counter --> GET: " + getRequestCounter + ", POST: " + postRequestCounter + ", PUT: " + putRequestCounter +", DELETE: " +deleteRequestCounter);
// Find a single patient by their id within save
Patient.findOne({ _id: req.params.id }, function (error, patient) {
// If there are any errors, pass them to next in the correct format
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)))
if (patients) {
// Send the patient if no issues
res.send(patient)
console.log('Sending response to GET request.');
} else {
// Send 404 header if the patient doesn't exist
res.send(404)
console.log("Error occurred in sending Response.");
}
})
})
// Create a new patient
server.post('/patients', function (req, res, next) {
postRequestCounter++;
console.log('received POST request.');
console.log("Processed Request Counter --> GET: " + getRequestCounter + ", POST: " + postRequestCounter + ", PUT: " + putRequestCounter +", DELETE: " +deleteRequestCounter);
// Make sure first_name is defined
if (req.params.first_name === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('first_name must be supplied'))
}
if (req.params.last_name === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('last_name must be supplied'))
}
if (req.params.blood_group === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('blood_group must be supplied'))
}
if (req.params.address === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('address must be supplied'))
}
if (req.params.date_of_birth === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('date_of_birth must be supplied'))
}
if (req.params.date_admitted === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('date_admitted must be supplied'))
}
if (req.params.department === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('department must be supplied'))
}
if (req.params.doctor === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('doctor must be supplied'))
}
if (req.params.ailment === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('ailment must be supplied'))
}
var newpatient = {
first_name: req.params.first_name,
last_name: req.params.last_name,
blood_gorup: req.params.blood_gorup,
address: req.params.address,
date_of_birth: req.params.date_of_birth,
date_admitted: req.params.date_admitted,
department: req.params.department,
doctor: req.params.doctor,
ailment:req.params.ailment
}
// Create the patient using the persistence engine
Patient.create( newpatient, function (error, patient) {
// If there are any errors, pass them to next in the correct format
if (error) {
console.log('Error on creating patient.');
return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)));
}
// Send the patient if no issues
res.send(201, patient)
patientArray.push(patient);
console.log('patient Array: ' + patientArray);
})
console.log('Sending response to POST request.');
})
// Update a patient by their id
server.put('/patients/:id', function (req, res, next) {
putRequestCounter++;
console.log('received PUT request.');
console.log("Processed Request Counter --> GET: " + getRequestCounter + ", POST: " + postRequestCounter + ", PUT: " + putRequestCounter +", DELETE: " +deleteRequestCounter);
// Make sure first_name is defined
if (req.params.first_name === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('first_name must be supplied'))
}
if (req.params.last_name === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('last_name must be supplied'))
}
if (req.params.blood_group === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('blood_group must be supplied'))
}
if (req.params.address === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('address must be supplied'))
}
if (req.params.date_of_birth === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('date_of_birth must be supplied'))
}
if (req.params.date_admitted === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('date_admitted must be supplied'))
}
if (req.params.department === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('department must be supplied'))
}
if (req.params.doctor === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('doctor must be supplied'))
}
if (req.params.ailment === undefined ) {
// If there are any errors, pass them to next in the correct format
return next(new restify.InvalidArgumentError('ailment must be supplied'))
}
var newpatient = {
first_name: req.params.first_name,
last_name: req.params.last_name,
blood_group: req.params.blood_group,
address: req.params.address,
date_of_birth: req.params.date_of_birth,
date_admitted: req.params.date_admitted,
department: req.params.department,
doctor: req.params.doctor,
ailment:req.params.ailment
}
// Update the patient with the persistence engine
Patient.update(newpatient, function (error, patient) {
// If there are any errors, pass them to next in the correct format
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)))
console.log('Sending response to PUT request.');
// Send a 200 OK response
res.send(200)
})
})
// Delete patient with the given id
server.del('/patients/:id', function (req, res, next) {
deleteRequestCounter++;
console.log('received DELETE request.');
console.log("Processed Request Counter --> GET: " + getRequestCounter + ", POST: " + postRequestCounter + ", PUT: " + putRequestCounter +", DELETE: " +deleteRequestCounter);
// Delete the patient with the persistence engine
Patient.delete(req.params.id, function (error, patient) {
// If there are any errors, pass them to next in the correct format
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)))
// Send a 200 OK response
res.send()
console.log('Sending response to DELETE request.');
})
})
// Delete all patients in the system
server.del('/patients', function (req, res) {
deleteRequestCounter++;
console.log('received DELETE request.');
console.log("Processed Request Counter --> GET: " + getRequestCounter + ", POST: " + postRequestCounter + ", PUT: " + putRequestCounter +", DELETE: " +deleteRequestCounter);
// Find every entity within the given collection
Patient.deleteMany({}, function (error) {
// Return all of the patients in the system
res.send()
console.log('Sending response to DELETE request.');
})
})
My PACKAGE.JSON
{
"name": "patients",
"version": "1.0.0",
"description": "REST API - Patients",
"dependencies": {
"mongod": "^2.0.0",
"mongodb": "^3.1.8",
"mongoose": "^5.3.9",
"restify": "4.1.1",
"save": "2.3.0"
},
"author": "Oguz Bayral",
"private": true,
"main": "index.js",
"scripts": {
"start": "node index.js"
}
}
Also I have a Procfile which is like below:
web: node index.js
And the Heroku log is like below:
2018-11-14T23:56:12.120061+00:00 heroku[web.1]: State changed from
crashed to starting
2018-11-14T23:56:12.000000+00:00 app[api]: Build succeeded
2018-11-14T23:56:14.581822+00:00 heroku[web.1]: Starting process with
command `node index.js`
2018-11-14T23:56:18.630046+00:00 app[web.1]: No process.env.IP var,
using default: 127.0.0.1
2018-11-14T23:56:18.658574+00:00 app[web.1]: (node:4)
DeprecationWarning: current URL string parser is deprecated, and will
be removed in a future version. To use the new parser, pass option {
useNewUrlParser: true } to MongoClient.connect.
2018-11-14T23:56:18.678981+00:00 app[web.1]: Server healthrecords
listening at http://127.0.0.1:35354
2018-11-14T23:56:18.679175+00:00 app[web.1]: Resources:
2018-11-14T23:56:18.679289+00:00 app[web.1]: /patients
2018-11-14T23:56:18.679422+00:00 app[web.1]: /patients/:id
2018-11-14T23:56:18.982348+00:00 app[web.1]: Successfully connected to:
mongodb://tekstil:teksdev07#ds151753.mlab.com:51753/mapd713groupproject
2018-11-14T23:57:15.011331+00:00 heroku[web.1]: Error R10 (Boot
timeout) -> Web process failed to bind to $PORT within 60 seconds of
launch
2018-11-14T23:57:15.011331+00:00 heroku[web.1]: Stopping process with
SIGKILL
2018-11-14T23:57:15.126155+00:00 heroku[web.1]: Process exited with
status 137
2018-11-14T23:57:15.160113+00:00 heroku[web.1]: State changed from
starting to crashed
2018-11-14T23:57:17.940918+00:00 heroku[router]: at=error code=H10
desc="App crashed" method=GET path="/" host=mapd713prjct.herokuapp.com
request_id=bfd7440d-f39b-4823-947f-41fe01b740f2 fwd="199.212.27.182"
dyno= connect= service= status=503 bytes= protocol=https
2018-11-14T23:57:19.963685+00:00 heroku[router]: at=error code=H10
desc="App crashed" method=GET path="/favicon.ico"
host=mapd713prjct.herokuapp.com request_id=67de28c3-268f-4a8f-9f2e-
5c09142df654 fwd="199.212.27.182" dyno= connect= service= status=503
bytes= protocol=https
With you're current config, you're binding your server to localhost (127.0.0.1), Heroku doesn't say what IP to bind to, so you'll just have to bind to all of the available network interfaces, now Heroku should be able to detect your app.
// change
server.listen(port, ipaddress, function () {
console.log('Server %s listening at %s', server.name, server.url)
console.log('Resources:')
console.log(' /patients')
console.log(' /patients/:id')
})
//to
server.listen(port, function () {
console.log('Server %s listening at %s', server.name, server.url)
console.log('Resources:')
console.log(' /patients')
console.log(' /patients/:id')
})

Loopback/Strongloop failed with ssh2 function callback Error: write ECONNABORTED

I want to have a REST API that would return in web browser some cisco router CLI output from Cisco CLI command inputs via REST request using ssh2 and loopback.
I can't figure it out because of these errors.
The code below will run a few milliseconds returning some correct and expected output but then breaks the loopback instance at server side will break/stop.
Error encountered:
C:\LOCAL_APPS\Loopback\filedir\node_modules\async\dist\async.js:955
if (fn === null) throw new Error("Callback was already called.");
^
Error: Callback was already called.
at C:\LOCAL_APPS\Loopback\filedir\node_modules\async\dist\async.js:955:32
at C:\LOCAL_APPS\Loopback\filedir\node_modules\async\dist\async.js:3871:13
at interceptInvocationErrors
(C:\LOCAL_APPS\Loopback\filedir\node_modules\strong-remoting\lib\remote-
objects.js:713:22)
at C:\LOCAL_APPS\Loopback\filedir\node_modules\loopback-phase\node_modules\async\lib\async.js:154:25
at C:\LOCAL_APPS\Loopback\filedir\node_modules\loopback-phase\node_modules\async\lib\async.js:154:25
at C:\LOCAL_APPS\Loopback\filedir\node_modules\loopback-phase\node_modules\async\lib\async.js:154:25
at C:\LOCAL_APPS\Loopback\filedir\node_modules\strong-remoting\lib\remote-objects.js:679:7
at C:\LOCAL_APPS\Loopback\filedir\node_modules\strong-remoting\lib\http-context.js:305:7
at callback (C:\LOCAL_APPS\Loopback\filedir\node_modules\strong-remoting\lib\shared-method.js:
Stream :: close :: code: 0, signal: undefined
events.js:183
throw er; // Unhandled 'error' event
^
Error: write ECONNABORTED
at _errnoException (util.js:1024:11)
at Socket._writeGeneric (net.js:767:25)
at Socket._write (net.js:786:8)
at doWrite (_stream_writable.js:387:12)
at writeOrBuffer (_stream_writable.js:373:5)
at Socket.Writable.write (_stream_writable.js:290:11)
at Socket.write (net.js:704:40)
at SSH2Stream.ondata (_stream_readable.js:639:20)
Under common/models/device.js:
'use strict';
module.exports = function(Device) {
Device.getIPInterfaceBrief = function(ipaddr,cb){
var filter = {
include:{
relation: 'infosheet',
scope:{
fields:['data']
}
}
}
var Client = require('ssh2').Client;
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.exec('show ip int br', function(err, stream) {
if (err) throw err;
stream.on('close', function(code, signal) {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', function(data) {
cb(null,"data: " + 'done') //or cb(null,"data: " + data)
console.log('STDOUT: ' + data);
}).stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
});
}).connect({
host: ipaddr,
port: 22,
username: 'routerusername',
password: 'passwordhere'
});
console.log("check 1");
};
Device.remoteMethod('getIPInterfaceBrief',{
description: "Returns the brief interface information of a device",
accepts:{
arg:'ipaddr',
type: 'string',
required: false
},
http:{
path:'/:ipaddr/getIPInterfaceBrief',
verb: 'get'
},
returns:{
arg:'interfaceinfo',
type:'any'
}
});
}; //module.exports
REST TEST URL:
http:// localhost:3000/api/adevices/some-ip-here/getIPInterfaceBrief
Error encountered after few seconds API responded the get REST request:
I temporarily added some try catch statement it worked somehow.
I think loopback is not part of the issue.
Hope you have better fix since the code works on other machines like Linux system but for Cisco routers have some problem with the line "conn.end".
Added try and catch to capture the errors..
if (err) throw err;
stream.on('close', function(code, signal) {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
try {
conn.end();
}catch (err){
console.log("error occured",err);
}
}).on('data', function(data) {
console.log('STDOUT: ' + data);
}).stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
My test did capture the error see here

Categories

Resources