I am new to Node.js and I have been trying to create a small app integrated with KUE library for task queuing.
When I trying to run the app i.e. node app.js I get the following error:
{ ReplyError: ERR wrong number of arguments for 'set' command
at parseError (.......\node_modules\redis-parser\lib\parser.js:193:12)
at parseType (........\node_modules\redis-parser\lib\parser.js:303:14)
command: 'SET',
args: [ 'promotion:lock', 'H5BCCsomeRandomString==', 'PX', 2000, 'NX' ],
code: 'ERR' }
I did see this error at a lot of places but they all dont seem to be a solution for my problem.
Here is my app.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var dotenv = require('dotenv');
dotenv.load();
var queue = require('./routes/queueJob');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/jobs', queue);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
app.listen(3000);
And here is the routes/queuejob.js
var express = require('express');
var router = express.Router();
var kue = require('kue'),
jobs = kue.createQueue();
var env = {};
jobs.on('ready', () => {
console.info('Queue is ready!');
});
jobs.on('error', (err) => {
console.error('There was an error in the main queue!');
console.error(err);
console.error(err.stack);
});
router.get('/addnewjob', function(req, res) {
let callback = function() {
console.log('Callback has been triggered');
}
newJob('Request Job', callback);
res.end('Successfully added a new job');
});
function newJob(name, callback) {
name = name || 'Default_Name';
var job = jobs.create('new job', {
name: name
});
job
.on('complete', function() {
console.log('Job', job.id, 'with name', job.data.name, 'is done');
callback();
})
.on('failed', function() {
console.log('Job', job.id, 'with name', job.data.name, 'has failed');
callback();
})
job.save();
}
jobs.process('new job', function(job, done) {
setTimeout(function() {
console.log('Job Processing finished');
}, 5000);
done();
});
module.exports = router;
Since there isnt much in the error message I am not sure how to fix this issue. I would really appreciate some help on this.
A SET command in Redis has the following format:
SET key value [EX seconds] [PX milliseconds] [NX|XX]
In your error, it seems that you are trying to use the SET commands with many argurments that do not match the format:
command: 'SET',
args: [ 'promotion:lock', 'H5BCCsomeRandomString==', 'PX', 2000, 'NX' ],
Related
I want to show you my error with NodeJS and MySQL.
Error is at line 45 of app.js
Cannot read property 'end' of undefined
at ServerResponse.<anonymous> (/usr/my_server/app.js:45:24)
It happen when I call a request from 'addReferFriend.js' file.
I link here the two files that I am using.
app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql= require('mysql2');
var http = require('http');
var app = express();
var addReferFriend = require('./addReferFriend');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(async function(req, res, next) {
try {
if( req.dbConnection ) {
// ensure that req.dbConnection was not set already by another middleware
throw new Error('req.dbConnection was already set')
}
let connection = mysql.createConnection({
host: 'xx',
user: 'xx',
password: 'xx',
database: 'xx'
});
res.on("finish", function() {
// end the connection after the resonponse was send
req.dbConnection.end()
});
// wait for the connection and assign it to the request
req.dbConnection = await connection.connect();
next();
} catch(err) {
next(err);
}
});
app.use('/api/addReferFriend', addReferFriend);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
var server = http.createServer(app);
server.listen(3955);
addReferFriend.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.post('/', function(req, res, next) {
var uid = req.body.uid;
var friendReferCode = req.body.friendReferCode;
var sqlCheckIfExist = "SELECT my_refer FROM hub_user WHERE my_refer = '" + friendReferCode + "'";
var sqlCodeCheckSameAsMine = "SELECT my_refer FROM hub_user WHERE uid = '" + uid + "'";
function checkIfUserCodeExist() {
return req.dbConnection.query(sqlCheckIfExist)
.then(([rows, fields]) => {
if (rows == 0) {
console.log("Non esiste!")
return res.send(JSON.stringify({
"status": 500,
"response": "codeNotExist"
}));
}
console.log("Esiste!")
return checkIfCodeIsSameAsMine(connection)
})
}
function checkIfCodeIsSameAsMine() {
return req.dbConnection.query(sqlCodeCheckSameAsMine)
.then(([rows, fields]) => {
if (rows == friendReferCode) {
console.log("Codice uguale!")
return res.send(JSON.stringify({
"status": 500,
"response": "sameCodeAsMine"
}));
}
console.log("Codice non uguale!")
})
}
checkIfUserCodeExist()
.catch(next)
});
module.exports = router;
I have no idea how fix this type of problem. It happen when I call the checkIfUserCodeExist() and it doesn't join into the function and it gives directly the error. I can't print any of console.log because it break.
Hope that somebody can help me with this issue.
Thanks in advance for the help,
Michele.
it seems to be req.dbConnection.end() the problem... the object dbConnection is undefined.
is it possible that the connection is closed first for some reason? so the point to closing connection is not correct?
When a logged-in user gets to a page through the browser using EJS I'm able to get the function to do what it's supposed to but when I use the API with Ionic using a logged in user with JWT, the async.parallel function doesn't "wait" to do things in order.
Here is my function:
console.log('1');
async.parallel([
function(callback){
buildAlertButtonsArray.getRealTestAlerts(req,function(arrayAlerts) {
console.log('2');
callback(null, arrayAlerts);
});
},
function(callback) {
if(req.decoded) //API
callback('API');
else //EJS
functions.aclSideMenu(req, res, function (acl) {callback(null, acl);}); //aclPermissions sideMenu
}
],function(err, results){
console.log('3');
})
when I login through the browsed on my console.log() is 1, 2, 3 but when I login through the API using JWT I get 1, 3, 2.
Here is my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var bluebird = require('bluebird');
//me
var mongoose = require('mongoose');
var db = mongoose.connection;
var cors = require('cors');
var session = require('client-sessions');
var flash = require('express-flash');
//.js file
var routesApi = require('./routes/api');
var routesEjs = require('./routes/ejs');
var routes = require('./routes/index');
//var login = require('./routes/authentication/login');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); //was FALSE by default. was TRUE for auth Template
// middleware
app.use(session({
cookieName: 'session',
secret: 'mysecret',
duration: 30 * 60 * 1000,
activeDuration: 30 * 60 * 1000,
httpOnly: true, //doesn't let javascript access cookies ever
secure: true, // only use cookies over https
ephemeral: true // delete this cookie when the browser is closed (nice when people use public computers)
}));
app.use(flash());
app.use(function(req, res, next){
res.locals.success_messages = req.flash('success_messages');
res.locals.error_messages = req.flash('error_messages');
next();
});
// use cors
app.use(cors());
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/api', routesApi);
app.use('/', routes);
app.use('/', routesEjs);
//bluebird
mongoose.Promise = require('bluebird');
//connecting to database
mongoose.connect('mongodb://myip:2999/SMECS_database', { useMongoClient: true });
//if we connect successfully or if a connection error occurs
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
// error handlers
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is my Login function for both EJS using CSRF and API using JWT:
module.exports.postLogin = function(req, res, next) {
if (req.body.pushToken) { // run SMECS API
models.Users.findOne({
email: req.body.email.toLowerCase()
}, function (err, user) {
if (err) throw err;
if (!user) {
res.json({success: false, message: 'Authentication failed. User not found.'});
} else if (user) {
//check if password matches
if (!bcrypt.compareSync(req.body.pin, user.pin)) {
res.json({success: false, message: 'Authentication failed. Wrong password.'});
} else {
// if user is found and password is right
// create a token
var token = jwt.sign({user: user}, config.secret, {
//expiresIn: 1440 // expires in 24 hours
});
user.save(function (err) {
if (err) {
res.json({
success: false,
message: 'contact your system administrator. pushToken not saved'
});
} else {
// return the information including token as JSON
res.json({
success: true,
message: 'Welcome aboard!',
token: token,
userRoleID: user.userRoleID,
userRoleName: user.userRoleName,
userPrivilegeID: user.userPrivilegeID,
userPrivilegeName: user.userPrivilegeName,
firstName: user.firstName,
lastName: user.lastName,
email: user.email
});
}
});
}
}
});
}
else { //run SMECS EJS
models.Users.findOne({email: req.body.email.toLowerCase()}, function (err, user) {
if (!user || user.softDeleted !== null) {
//Parent Self Registration Login
models.ParentSelfRegistration.findOne({email: req.body.email.toLowerCase()}, function (err, parentSelfRegistration) {
if (!parentSelfRegistration) {
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
} else {
if (req.body.pin == parentSelfRegistration.pin) {
req.session.user = parentSelfRegistration;
res.redirect('/parentsSelfRegistration/registerParentStep1');
} else {
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
}
}
});
//END OF checks for users in UtilityUsers database
} else {
if (bcrypt.compareSync(req.body.pin, user.pin)) { // if user is found and password is right
req.session.user = user;
res.redirect('/dashboard');
//}
} else {
//res.status(400).send('Current password does not match');
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
//res.render('login', { error: "ERROR: Incorrect email or pin."});
}
}
});
}
};
Here is my ejs.js file:
//Dependencies
var express = require('express');
var routerEjs = express.Router();
var login = require('./authentication/login');
var auth = require('./authentication/auth');
var chooseAlert = require('./alerts/sendingReceiving/1.chooseAlert');
var login = require('./authentication/login');
var csrf = require('csurf');
routerEjs.use(csrf());
/* GET login page. */
routerEjs.get('/login', login.getLogin, function(req, res) {});
routerEjs.post('/login', login.postLogin, function(req, res) {});
routerEjs.get('/logout', login.getLogout, function(req, res) {});
module.exports = routerEjs;
and my api.js file:
//Dependencies
var express = require('express');
var routerApi = express.Router();
var login = require('./authentication/login');
var auth = require('./authentication/auth');
var chooseAlert = require('./alerts/sendingReceiving/1.chooseAlert');
routerApi.post('/login', login.postLogin, function(req, res) {});
routerApi.get('/chooseGroup', auth.auth, chooseAlert.showGroups, function(req, res) {});
routerApi.get('/alerts/sending/chooseAlert', auth.auth, chooseAlert.showAlerts, function(req, res) {});
/* Update pushToken ------------------------------------*/
routerApi.post('/updatePushToken', auth.auth, auth.pin, function(req, res) {});
module.exports = routerApi;
I figured out my problem. I was missing a NULL on my callback...
console.log('1');
async.parallel([
function(callback){
buildAlertButtonsArray.getRealTestAlerts(req,function(arrayAlerts) {
console.log('2');
callback(null, arrayAlerts);
});
},
function(callback) {
if(req.decoded) //API
callback(NULL, 'API');
else //EJS
functions.aclSideMenu(req, res, function (acl) {callback(null, acl);}); //aclPermissions sideMenu
}
],function(err, results){
console.log('3');
})
I'm currently trying to get a node.js/express tutorial working (from Express in Action), but haven't been able to access a mongoose model properly. I call the module in a var called "User" I keep getting the error that "User.find is not a function."
Here is the models/user.js file:
var
bcrypt = require("bcrypt-nodejs"),
mongoose = require("mongoose"),
SALT_FACTOR = 10
;
var noop = function() {};
var userSchema = mongoose.Schema({
displayName: String,
bio: String
});
userSchema.pre("save", function(done) {
var user = this;
if (!user.isModified("password")) {
return done();
}
bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
if (err) { return done(err); }
bcrypt.hash(user.password, salt, noop, function(err, hashedPassword) {
if (err) { return done(err); }
user.password = hashedPassword;
done();
});
});
});
userSchema.methods.checkPassword = function(guess, done) {
bcrypt.compare(guess, this.password, function(err, isMatch) {
done(err, isMatch);
});
};
userSchema.methods.name = function() {
return this.displayName || this.username;
};
var User = mongoose.model("User", userSchema);
module.exports = User;
Here is the routes.js file calling it:
var
express = require("express"),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
router = express.Router()
;
var User = ("./models/user");
router.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.errors = req.flash("error");
res.locals.infos = req.flash("info");
next();
});
router.get("/", function(req, res, next) {
User.find({}, function(err, users) {
assert.equal(err, null);
res.json(users);
});
});
/*
Original route, also doesn't work
router.get("/", function(req, res, next) {
User.find()
.sort({ createdAt: "descending" })
.exec(function(err, users) {
if (err) { return next(err); }
res.render("index", { users: users });
});
});
*/
module.exports = router;
Lastly here's the index.js file, in case it's relevant
var
http = require("http"),
path = require("path"),
express = require("express"),
flash = require("connect-flash"),
session = require("express-session"),
cookieParser = require("cookie-parser"),
logger = require("morgan"),
liquid = require("shopify-liquid"),
bodyParser = require("body-parser"),
mongoose = require('mongoose')
;
var routes = require('./routes');
var app = express();
mongoose.connect('mongodb://localhost:27017/test');
app.set("port", process.env.PORT || 3000);
var engine = liquid({
root: __dirname, // for layouts and partials
extname: '.liquid'
});
app.engine('liquid', engine.express());
app.set('views', ['./views', './views/partials', './views/layouts']);
app.set('view engine', 'liquid');
var assetsPath = path.resolve(__dirname, "assets");
app.use("/assets", express.static(assetsPath));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: "TKRv0IJs=HYqrvagQ#&!F!%V]Ww/4KiVs$s,<<MX",
resave: true,
saveUninitialized: true
}));
app.use(flash());
app.use(routes);
app.use(logger("dev"));
app.use(function(request, response) {
response.status(404).render("404");
});
http.createServer(app).listen(3000, function(){
console.log('App skeleton started on port 3000.');
});
I've tried the solutions suggested from all similar questions but had no luck.
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var path = require('path');
var bodyParser = require('body-parser');
var credentials = require('./credentials.js');
var session = require('express-session');
// set up handlebars view engine
app.set('views',path.join(__dirname,'public/views'));
app.set('view engine', 'hbs');
// setup
app.use(express.static(path.join(__dirname, 'public/assets')));
//db config
var configDB = require('./config/db.js');
mongoose.connect(configDB.url); // connect to our database
//mongoose session setup
const MongoStore = require('connect-mongo')(session);
var options = {
server: {
socketOptions: { keepAlive: 1 }
}
};
//body parser and session and cookie parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(require('cookie-parser')(credentials.cookieSecret));
app.use(require('express-session')({
resave: false,
saveUninitialized: false,
secret: 'iamsupersecret',
store: new MongoStore({url:configDB.url,options})
}));
// flash message middleware
app.use(function(req, res, next)
{
res.locals.flash = req.session.flash;
delete req.session.flash;
next();
});
// routes ======================================================================
require('./routes.js')(app);
// 404 catch-all handler (middleware)
app.use(function(req, res, next)
{
res.status(404);
res.render('404');
});
// 500 error handler (middleware)
app.use(function(err, req, res, next)
{
console.error(err.stack);
res.status(500);
res.render('500');
});
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
I am building a small app for buying tickets, for now i have a cart collection in my mongodb that saves the users cart using the session id. I want to instead save the data in a session-like manner, so that as soon as the user ends the session the cart is deleted and i won't need the database anymore because i do not need the carts data as i have a sales data for all the logistics i need. below is my cart controller showing how i currently save data to my cart collection.
exports.addItem = function (req, res)
{
if(!userKey)
{
userKey = req.session.id;
}
Cart.findOne({userKey : userKey},function (err, cart)
{
if(err)
{
console.log("Error finding cart "+err);
req.session.flash =
{
type: 'danger',
intro: 'Ooops!',
message: 'There was an error finding your cart.'
};
return res.redirect(303, '/cart');
}
else if(!cart)
{
cart = new Cart();
cart.userKey = userKey;
cart.items = [];
Ticket.findOne({_id:req.params.id},function (err, ticket)
{
if(err)
{
console.log("Error finding ticket "+err);
req.session.flash =
{
type: 'danger',
intro: 'Ooops!',
message: 'There was an error finding that ticket.'
};
return res.redirect(303, '/cart');
}
var item = {
id:ticket._id,
type: ticket.type,
price: ticket.price,
quantity: 1,
time: ticket.time,
date: ticket.date
};
cart.items.push(item);
cart.save();
return res.redirect(303,'/cart');
});
}
else if(cart)
{
Ticket.findOne({_id:req.params.id},function (err, ticket)
{
if (err)
{
console.log("Error finding ticket "+err);
req.session.flash =
{
type: 'danger',
intro: 'Ooops!',
message: 'There was an error finding that ticket.'
};
return res.redirect(303, '/cart');
}
else
{
var item =
{
id:ticket._id,
type: ticket.type,
price: ticket.price,
quantity: 1,
time: ticket.time,
date: ticket.date
};
cart.items.push(item);
cart.save();
return res.redirect(303,'/cart');
}
});
}
});
};
as explain in this answer try to link it with cookies
app.use(express.session({cookie: { path: '/', httpOnly: true, maxAge: null}, secret:'eeuqram'}));
maxAge: null will make sure that session expires after browser is closed.
app.js
var express = require('express');
var express_namespace = require('express-namespace');
var path = require('path');
var favicon = require('serve-favicon');
var http = require('http');
var https = require('https');
var e_logger = require('morgan');
var logger = require('./logger.js').getLogger('framework');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var awsControl = require('./routes/awsControl')
var aws = require('aws-sdk');
var ec2 = new aws.EC2();
var app = express();
var server = http.createServer(app);
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.set('port', 80);
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(cookieParser());
app.use(e_logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use('/', routes);
}
// routes
app.namespace('/', function () {
app.get('describeInstances', awsControl.describeInstances);
});
server.listen(app.get('port'), function () {});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404
logger.error(err);
next(err);
});
awsControl.js
var aws = require('aws-sdk');
var util = require('util');
aws.config.update({
accessKeyId: "myKey",
secretAccessKey: "mySecretKey",
region: "ap-northeast-1"
});
console.log("config = " + util.inspect(aws.config));
var ec2 = new aws.EC2({ region: "ap-northeast-1" });
var app01 = 'aaaaaaaa';
var DB01 = 'bbbbbbbb';
exports.describeInstances = function (req, res) {
var params = {
Filters: [{
Name: 'vpc-id',
Values: ['vpc-cccccccc']
}],
DryRun: false
};
ec2.describeInstances(params, function (err, data) {
if (err) { // an error occurred
console.log(err, err.stack);
} else { // successful response
console.log(data);
}
});
}
control.js
var Control = function () {
this.initializePage();
};
Control.prototype = new Object();
Control.prototype = {
initializePage : function () {
$.ajax({
type: "GET",
url: "describeInstances",
success : function (data, status, jQxhr) {
console.log("### describeInstances success");
console.log(data);
},
error : function (jQxhr, status, error) {
console.log("### describeInstances error");
console.log(error);
console.log(jQxhr);
},
complete : function (jQxhr, status) {
console.log("### describeInstances complete");
console.log(jQxhr);
}
});
}
}
I programmed like above and the node web server is operating well.
awsControl.js is server-side javascript and control.js is client-side javascript.
When I connect to my web server, Control class is called first.
Here is the trouble. When I send request with startInstance (AWS-SDK API), it's working in server-side.
However, I can't receive response with 503 error(service unavailable).
On client-side, I always receive error callback with 503 error.
I don't know why I can't receive response.
I set security groups(EC2) and NACL(VPC) up so I don't think that it's firewall trouble.
Is there anybody can tell me how I can find the solution out?
I have done this.
ec2.describeInstances(params, function (err, data) {
if (err) { // an error occurred
console.log(err, err.stack);
} else { // successful response
console.log(data);
res.send(data); <-- this line
}
});
I added just a line I focus to awsControl.js file, then done.