Undefined result when not using callback. Nodejs, Express, and SQL Server Express - node.js

The following issue consists of mssql, Nodejs, Gulp, Express, and SQL Server Express. I am able to login to SQL Server Express successfully. However, the returned value is undefined when I use the bookRoute.js code snippet without callback. Yet, when I use a callback I get the data. However, I don't understand why.
app.js code snippet:
var config = {
user: 'user',
password: 'password',
server: 'localhost',
database: 'Books',
options: {
instance: 'SQLEXPRESS'
}
};
sql.connect(config, function(err){
console.log(err);
});
bookRoute.js code snippet without callback:
bookRouter.route('/')
.get(function (req, res) {
console.log('book router');
var request = new sql.Request();
request.query('select * from books').then(
function (err, recordset) {
console.log(recordset);
})
.catch(function(err){ console.log(err)});
});
bookRoute.js code snippet with callback:
bookRouter.route('/')
.get(function (req, res) {
console.log('book router');
var request = new sql.Request();
request.query('select * from books',
function (err, recordset) {
console.log(recordset);
});
});
Once a user accesses the webpage, then the console should display the results. Unfortunately, the only result that is shown is undefined when not using a callback.
console output:
P:\ub\lic\library>gulp serve
[11:08:28] Using gulpfile P:\ub\lic\library\gulpfile.js
[11:08:28] Starting 'style'...
[11:08:28] Starting 'inject'...
[11:08:53] Finished 'inject' after 808 ms
[11:08:53] Finished 'style' after 25 s
[11:08:53] Starting 'serve'...
[11:08:53] Finished 'serve' after 5.31 ms
[11:08:53] [nodemon] 1.9.2
[11:08:53] [nodemon] to restart at any time, enter `rs`
[11:08:53] [nodemon] watching: *.js src/**/*.js
[11:08:53] [nodemon] starting `node app.js`
running server on port 3000
null
book router
undefined
[11:09:21] [nodemon] restarting due to changes...
Restarting the server.....beep boop beep beep
[11:09:21] [nodemon] restarting due to changes...
Restarting the server.....beep boop beep beep
[11:09:21] [nodemon] starting `node app.js`
running server on port 3000
null
book router
[ { id: 1,
title: 'A,B,C with Big Bird ',
author: 'Michael Jacob ' },
{ id: 2,
title: 'Peter and his Petunias ',
author: 'Jess Holiday ' },
{ id: 3,
title: 'The Amazing Average Guy ',
author: 'Don Dillon ' } ]

bookRoute.js code snippet without callback:
bookRouter.route('/').get(function (req, res) {
console.log('book router');
var request = new sql.Request();
request.query('select * from books')
.then(function (recordset) {
console.log(recordset);
})
.catch(function (err) {
console.log(err);
});
});
When using bookRoute.js code snippet without callback.The then function should have only one argument that is the result from the query that is how it is stated in the documentation.When there is an error the catch function is called.

Related

How can we get & post request of same model object at same route at same time?

I am new to nodejs and i just started learning..I am trying to show the form data in table at
same time without restarting the server ..I need to update the changes at runtime
Below is the code of index.js where i have created routes,get and post request.
**var express = require('express');
var empModel = require('../modules/employee') //importing model object
var router = express.Router();
var employee = empModel.find({}); //storing model object in employee
/* GET home page. */
router.get('/', function(req, res, next) {
employee.exec(function(err,data){
if (err) throw err;
res.render('index', { title: 'Employee records' , records:data });
})
});
//post request of form
router.post('/', function (req, res, next) {
var empDetails = new empModel({
name : req.body.ename,
email : req.body.eemail,
etype : req.body.eetype,
hourlyrate : req.body.ehourrate,
totalhour : req.body.etotalhour,
total : parseInt(req.body.ehourrate) * parseInt(req.body.etotalhour) ,
})
empDetails.save(function(err,res1){
if(err) throw err;
employee.exec(function(err,data){
if (err) throw err;
res.render('index', { title: 'Employee records' , records:data });
})
});
});
module.exports = router;**
on staring the server error is :
PS C:\Users\harsh\Desktop\Employee> npm start
npm WARN config global --global, --local are deprecated. Use --location=global instead.
employee#0.0.0 start
node ./bin/www
GET / - - ms - -
node:events:505
throw er; // Unhandled 'error' event
^
MongooseError: Query was already executed: Employee.find({})
at model.Query._wrappedThunk [as _find] (C:\Users\harsh\Desktop\Employee\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19)
at C:\Users\harsh\Desktop\Employee\node_modules\kareem\index.js:426:25
at processTicksAndRejections (node:internal/process/task_queues:78:11)
Emitted 'error' event on Function instance at:
at C:\Users\harsh\Desktop\Employee\node_modules\mongoose\lib\model.js:4996:15
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
originalStack: 'Error\n' +
' at model.Query._wrappedThunk [as _find] (C:\Users\harsh\Desktop\Employee\node_modules\mongoose\lib\helpers\query\wrapThunk.js:25:28)\n' +
' at C:\Users\harsh\Desktop\Employee\node_modules\kareem\index.js:426:25\n' +
' at processTicksAndRejections (node:internal/process/task_queues:78:11)'
}
But if i use only employee.save() without function then the form data get posted and after
restarting the server again the data is showing in table but i want the data to be updated at
the same time so i used rendering again as mentioned in above code.

Node js server crashes after PUT request

After making a put request, the app crashes with error
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
(node:21666) 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.
(Use `node --trace-deprecation ...` to show where the warning was created)
Server up and running
(node:21666) DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify` option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#findandmodify
node:internal/process/promises:227
triggerUncaughtException(err, true /* fromPromise */);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:329:5)
at ServerResponse.setHeader (node:_http_outgoing:572:11)
at ServerResponse.header (/Users/kayode/Desktop/learn-mern/auth/node_modules/express/lib/response.js:771:10)
at ServerResponse.json (/Users/kayode/Desktop/learn-mern/auth/node_modules/express/lib/response.js:264:10)
at ServerResponse.send (/Users/kayode/Desktop/learn-mern/auth/node_modules/express/lib/response.js:158:21)
at /Users/kayode/Desktop/learn-mern/auth/routes/users.js:36:24
at processTicksAndRejections (node:internal/process/task_queues:94:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
Here is my code...
const router = require('express').Router();
const User = require('../models/User')
router.put('/:email', async (req, res, next) => {
res.send(req.params._id)
let email = req.params.email;
let user = {
name: req.body.name,
email: req.body.email,
password: req.body.password
}
try {
await User.findOneAndUpdate(email, user);
res.status(200).send(JSON.stringify('200'));
console.log('Here first')
} catch (err) {
res.status(400).send(err) //not commented
}
})
module.exports = router;
But, if I try to make a another request (with postman), without refreshing the server it says sends a error could not send request
But then again, on line 36, "at /Users/kayode/Desktop/learn-mern/auth/routes/users.js:36:24" where it says res.status(400).send(err) //not commented
if I comment the line out (ie not return an error), the PUT request would be successful and another request after that would also work without refreshing or restartiung the server.
I know I can just comment that line out and move on, but I need to know what's happening, thanks!
You are sending the response in the beginning of the request and try to send it again in the end of the request (in line5) .
const router = require('express').Router();
const User = require('../models/User')
router.put('/:email', async (req, res, next) => {
let email = req.params.email;
let user = {
name: req.body.name,
email: req.body.email,
password: req.body.password
}
try {
await User.findOneAndUpdate(email, user);
res.status(200).send(JSON.stringify('200'));
console.log('Here first')
} catch (err) {
res.status(400).send(err) //not commented
}
})
module.exports = router;

TypeError: Arguments to path.join must be strings NodeJS

I'm creating a simple web API using NodeJS express, for some home domotics. For my TV I'm using the following library --> https://github.com/hobbyquaker/lgtv2.
When I run my code locally, for example;
var lgtv = require('lgtv2')({
url: 'ws://192.168.178.31:3000'
});
lgtv.on('error', function(err) {
console.log(err);
});
lgtv.on('connect', function() {
console.log('connected');
lgtv.request('ssap://system/turnOff', function(err, res) {
lgtv.disconnect();
});
});
It run's fine. However, the same code, deployed to my Synology NAS, results in an error.
TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at exports.join (path.js:358:36)
at module.exports (/volume1/web/NodeJS/node_modules/persist-path/index.js:19:22)
at new LGTV (/volume1/web/NodeJS/node_modules/lgtv2/index.js:47:16)
at LGTV (/volume1/web/NodeJS/node_modules/lgtv2/index.js:38:16)
at Object.module.exports.setNetflix (/volume1/web/NodeJS/controllers/tv.js:50:36)
at /volume1/web/NodeJS/routes/routes.js:43:12
at Layer.handle [as handle_request] (/volume1/web/NodeJS/node_modules/express/lib/router/layer.js:95:5)
at next (/volume1/web/NodeJS/node_modules/express/lib/router/route.js:137:13)
The only actual difference I can spot is the NPM version, which is v10.14.1 locally and v0.10.48 on my NAS. Is there any way to bypass this problem and get this working?
Randy
It is very strange library.
Try this code
console.log('Platform = ',process.platform);
var lgtv = require('lgtv2')({
url: 'ws://192.168.178.31:3000',
clientKey: ''
});
lgtv.on('error', function(err) {
console.log(err);
});
lgtv.on('connect', function() {
console.log('connected');
lgtv.request('ssap://system/turnOff', function(err, res) {
lgtv.disconnect();
});
});

Can't connect to Socket.io Error: xhr poll error

Hi i'm using Homestead with a laravel application.
I can't get the client to receive the data on from the server...
My socket.js:
var server = require('http').Server();
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel');
redis.on('message', function (channel, message) {
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
/*Booting Up the Server : port 3000 */
server.listen(3000 , function(){
console.log('The Server Is Running');
});
This is listening to port 3000 which is working.
Console output:
vagrant#homestead:~/code/chatting-app$ nodemon -L socket.js
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node socket.js`
The Server Is Running
On the client side i'm also listening to port 3000.
i use a piece of code to display the error:
function checkSocketIoConnect(url, timeout) {
return new Promise(function(resolve, reject) {
var errAlready = false;
timeout = timeout || 5000;
var socket = io(url, {reconnection: false, timeout: timeout});
// success
socket.on("connect", function() {
clearTimeout(timer);
resolve();
socket.close();
});
// set our own timeout in case the socket ends some other way than what we are listening for
var timer = setTimeout(function() {
timer = null;
error("local timeout");
}, timeout);
// common error handler
function error(data) {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (!errAlready) {
errAlready = true;
reject(data);
socket.disconnect();
}
}
// errors
socket.on("connect_error", error);
socket.on("connect_timeout", error);
socket.on("error", error);
socket.on("disconnect", error);
});
}
checkSocketIoConnect("http://192.168.10.10:3000").then(function() {
console.log('succes');
}, function(reason) {
console.log(reason);
});
But this displays the following error:
Error: xhr poll error
Stacktrace:
[14]</n.prototype.onError#https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js:1:24221
[17]</</o.prototype.doPoll/<#https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js:1:29697
[9]</n.prototype.emit#https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js:1:13388
[17]</</i.prototype.onError#https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js:1:31004
i don't know what to do?! I tried everything i can think of.
My homestead.Yaml file:
Any help is appreciated...
IT WAS ADBLOCKER
Disabled adblocker for this page and it works now.
Stupid.........

Mongoose hangs and I don't have any connection errors

I am working on my ubuntu, and this always hangs :
router.route('/articles')
// get all the articles (accessed at GET http://localhost:8080/api/articles)
.get(function(req, res) {
Article.find().sort('-created_at').exec(function(err, articles) {
if (err)
res.send(err);
res.json(articles);
});
});
but not just this one, it seems to be the same with all my collections, but I can see them fine in mongo shell or Robomongo.
I don't think it is a connection error because I don't have any :
// database
var mongoose = require('mongoose');
console.log(config.database);
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost:27017/test', function(err) {
if (err) {
console.err(err);
} else {
console.log('Connected');
}
});
mongoose.connection.on('error', function(err) {
if (err) {
console.err(err);
} else {
console.log('Connected');
}
});
Dont know if it's relevant but I have warnings when using the mongo shell :
2015-09-08T19:07:12.200+0100 I CONTROL [initandlisten]
2015-09-08T19:07:12.200+0100 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 31125 processes, 64000 files. Number of processes should be at least 32000 : 0.5 times number of files.
I am very surprised because it worked just a few days ago, I am starting to think I may have a problem with my system.
FYI my full project on github : https://github.com/mael-jarnole/website
I have been struggling with this issue the whole afternoon, and could'nt get anything done.
console
---------$ nodemon server.js
8 Sep 19:26:19 - [nodemon] v1.4.1
8 Sep 19:26:19 - [nodemon] to restart at any time, enter `rs`
8 Sep 19:26:19 - [nodemon] watching: *.*
8 Sep 19:26:19 - [nodemon] starting `node server.js`
mongodb://localhost:27017/test
Listening on: 8080
css file written on disk successfully !
Connected
Something is happening with the API.

Resources