How to set session value in callback? Why it doesn't work?
app.get('/room/:id', function(req, res) {
var room_id = req.param('id');
room.getRoom(room_id, function(err, result) {
if(result.length) {
req.session.code_room = room_id;
}
});
res.render('room.jade');
});
You probably should move res.render to the inside of callback function:
app.get('/room/:id', function(req, res) {
var room_id = req.param('id');
room.getRoom(room_id, function(err, result) {
if(result.length && !err) {
req.session.code_room = room_id;
} else {
//sorry...
req.session.code_room = -1;
}
res.render('room.jade');
});
});
Related
Below is my code where I want to check if a token exists. If yes, then I will check if the wallet owner is the token owner. Problem now is it doesn't check the second function "contract.methods.ownerOf(tokenId).call(function (err, res)" thus the final result is not the correct outcome.
async function doesTokenIdExist(tokenId, contract, walletAddress) {
var tokenExists = false;
await contract.methods.exists(tokenId).call(async function (err, res) {
if (res) {
await contract.methods.ownerOf(tokenId).call(function (err, res) {
if (!err) {
tokenAddress = res.toLowerCase();
walletAddress = walletAddress.toLowerCase();
if (tokenAddress.localeCompare(walletAddress) == 0){
tokenExists = true;
} else {
tokenExists = false;
}
} else {
tokenExists = false;
}
});
} else {
tokenExists = false;
}
});
return tokenExists;
}
Change this,
await contract.methods.exists(tokenId).call(function (err, res) {
to this,
await contract.methods.exists(tokenId).call(async function (err, res) {
I'm trying to check the entered username and password stored in a database.
My solution is not correct and I think there might be something better than my code.
Here it is thus far:
function login (username, password, callback) {
var query = "SELECT * FROM users WHERE username = ?";
connection.query(query, [username], function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
var user = results[0];
if (!bcrypt.compareSync(password, user.password)) {
return callback();
}
callback(null, {
id: user.id.toString(),
});
});
}
app.get('/salam', function (req, res) {
var username = 'mahdi';
var originalPassword = 'a';
login(username , originalPassword,function (callback) {
console.log(callback);
});
});
In my code, console.log(callback); returns null, but usernames and passwords are correct. How can I fix this?
In your success callback function, you are having 2 arguments but in error callback, only one argument.
In error and success case, value of first parameter will always be null and in if (!bcrypt.compareSync(password, user.password)) { case, value of first argument will be undefined as there is no value being passed as argument.
Suggestion: Use first argument as Boolean(false or true) and based on the value, handle the callback.
function login(username, password, callback) {
var query = "SELECT * FROM users WHERE username = ?";
connection.query(query, [username], function(err, results) {
if (err) return callback(false);
if (results.length === 0) return callback();
var user = results[0];
if (!bcrypt.compareSync(password, user.password)) {
return callback(false);
}
callback(true, {
id: user.id.toString(),
});
});
}
app.get('/salam', function(req, res) {
var username = 'mahdi';
var originalPassword = 'a';
login(username, originalPassword, function(success, value) {
if (success) {
console.log(value);
}
});
});
It should be, because you didn't pass anything in callback. Change like this :
function login (username, password, callback) {
var query = "SELECT * FROM users WHERE username = ?";
connection.query(query, [username], function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback(null, false);
var user = results[0];
if (!bcrypt.compareSync(password, user.password)) {
return callback(null, false);
}
callback(null, true, {
id: user.id.toString(),
});
});
}
app.get('/check', function (req, res) {
var username = 'mahdi';
var originalPassword = 'a';
login(username , originalPassword,function (err, result, id) {
console.log(err);
console.log(result);
console.log(id);
});
});
result is for finding out true|false of action. And id means when result is true
Also err for callback is needed to error handling
I have an express app where I'm calling a function with an API call.
The problem I'm having is getting the response from the API call out of
the function and back to the main router. I know this may have to do
with the code being processed asynchronously but I can't figure out
a way around the issue.
/* GET funnel page. */
router.get('/funnel', function(req, res, next) {
var score = 'test2';
score = GetQuery('Bars');
res.render('funnel', {title: score});
});
function GetQuery(query) {
var test = 'test3';
factual.get('/t/places-us', {q:query,limit: 1, filters:{"$and":[{"region":{"$eq":"NY"}},{"locality":"pittsford"}]}}, function (error, res) {
test = res.data[0].email;
});
return test;
}
You're right it does have something to do with asynchrony. The problem is that the API call does not block so you return immediately without reassigning the value. The simplest way to solve this would be to use a callback i.e.
/* GET funnel page. */
router.get('/funnel', function(req, res, next) {
var score = 'test2';
GetQuery('Bars', function(err, score) {
res.render('funnel', {title : score});
});
});
function GetQuery(query, cb) {
factual.get('/t/places-us', {q:query,limit: 1, filters:{"$and":[{"region":{"$eq":"NY"}},{"locality":"pittsford"}]}}, function (error, res) {
cb(error, res.data[0].email);
});
}
Another option would be to use a Promise or something like RxJS. Which would both let you use a more fluent style for your code:
Promise:
/* GET funnel page. */
router.get('/funnel', function(req, res, next) {
var score = 'test2';
GetQuery('Bars').then(function(score) {
res.render('funnel', {title : score});
});
});
var getQuery = Promise.denodify(factual.get);
function GetQuery(query) {
return getQuery('/t/places-us', /*Query parameters*/).then(function (res) {
return res.data[0].email;
});
}
RxJS
/* GET funnel page. */
router.get('/funnel', function(req, res, next) {
var score = 'test2';
GetQuery('Bars').subscribe(function(score) {
res.render('funnel', {title : score});
});
});
var getQuery = Rx.Observable.fromNodeCallback(factual.get, null,
function(res) {
return res.data[0].email;
});
function GetQuery(query) {
return getQuery('/t/places-us', /*Query*/);
}
Use callback
GetQuery('Bars', function(err,result){
res.render('funnel', {title: score});
});
function GetQuery(query,callback) {
var test = 'test3';
factual.get('/t/places-us', {q:query,limit: 1, filters:{"$and":[{"region":{"$eq":"NY"}},{"locality":"pittsford"}]}}, function (error, res) {
callback(error,es.data[0].email);
});
}
I' have this code, know that require anonymus closure function, but don't understand how it works. If I run it there is a TypeError: undefined is not a function.
Can some one explain me anonymus closure functions with the help of this code?
mysql= require('mysql');
var connection = mysql.createConnection({});
function check_auth(input, callback){
var sql = "query to mysql";
connection.query(sql, function(err, results) {
if (err) callback(err);
if (results.length > 0) {
callback(null,results.values); //this is the line with error
}else{
callback(null, false);
}
});
};
var io = require('socket.io').listen(5678);
io.configure(function () {
io.set('authorization', function(req, callback) {
check_auth(req.query.s, function(err, result) {
if (err) {
return console.log('error:(');
}
if(result === false) {
return callback('notauth', false);
} else {
return callback(null, result);;
}
});
});
});
You code looks good, but you have an error in your code: missing ); };
mysql= require('mysql');
var connection = mysql.createConnection({});
function check_auth(input, callback){
var sql = "query to mysql";
connection.query(sql, function(err, results) {
if (err) callback(err);
if (results.length > 0) {
callback(null,results.values); //this is the line with error
}else{
callback(null, false);
}
}); // missing );
}; // missing };
io.configure(function () {
io.set('authorization', function(req, callback) {
check_auth(req.query.s, function(err, result) {
if (err) {
return console.log('error:(');
}
if(result === false) {
return callback('notauth', false);
} else {
return callback(null, result);;
}
});
});
});
There seems to be scoping issue in your code. You can't really call a function from another scope without referencing that scope. if you do:
io.configure(function () {
io.set('authorization', function(req, callback) {
var check_auth = function(...) {}; // <=== local defined
// then you can call this way
check_auth(...);
}
}
Since your check_auth() is defined outside, the callback of io.set() has its own scope, it doesn't know anything about check_auth(). So you have to point to the scope that has check_auth() defined. Something like this:
var me = this; // <==== scope that has check_auth defined
io.configure(function () {
io.set('authorization', function(req, callback) {
// then you can call this way
me.check_auth(...);
}
}
Or you can do closure approach by assigning check_auth to a variable and call it inside the callback. Something like this:
var check_auth = function(...) {};
io.configure(function () {
io.set('authorization', function(req, callback) {
// then you can call this way
check_auth(...);
}
}
I'm a begginer in Node.JS and as a first tryout i'm implementing a small url shortening service that will get a request with an id parameter and redirect to the actual url after searching a cassandra database.
Below you can find my implementation.
var reqResponse;
app.get('/r/:id', function(req, res) {
reqResponse = res;
conn.connect(function(err, keyspace) {
if(err){
throw(err);
}
conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, redirectCallback);
});
});
function redirectCallback (err, results) {
if (err != null) {
//log
} else {
if (results.length > 0) {
results.every(function(row){
reqResponse.writeHead(config.redirectStatus, {
'Location': row[0].value
});
reqResponse.end();
return false;
});
} else {
reqResponse.send("There was a problem!");
return false;
}
}
conn.close();
return true;
}
It works fine, it does the job, but i'm having some doubts about that reqResponse "global" variable. I don't like it there.
Is there a way I could send "res" as a parameter to the redirectCallback function?
Thank you!
Yes there is: Create an anonymous function and use that to pass the parameter:
app.get('/r/:id', function(req, res) {
conn.connect(function(err, keyspace) {
if(err){
throw(err);
}
conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, function (err, results) { redirectCallback(err, res, results); } );
});
});
And your callback becomes:
function redirectCallback (err, res, results) {