if (token_count == 1) {
var user_name = rows[0].user_name;
next();
} else {
data = {
message :"Invalid Token"
}
res.send(data);
}
I need to pass user_name as a parameter from next(), the function which it gets called is as bellow,
router.post('/dashboard', function (req, res) {
// user_name must be fetched here
console.log("middleware next")
});
You can add data to the req object
if (token_count == 1) {
var user_name = rows[0].user_name;
req.user_name = user_name;
next();
}else{
data = {
message :"Invalid Token"
}
res.send(data);
}
router.post('/dashboard', function (req, res) {
// user_name must be fetched here
console.log(req.user_name)
});
Related
I'm trying to open places.ejs file by clicking the submit button on show.js page, just like the show.ejs page opens on clicking the submit button on new.ejs file, but a reference error is occurring. Please help me fix the error. I'm attaching herewith my routes.js code and a part of my index.js code Any help would be highly appreciable. Thank you
Here's my routes.js code
const { con, sessionStore } = require('./config/db');
exports.new = function (req, res) {
message = '';
if (req.method == "POST") {
const post = req.body;
const username = post.username;
const title = post.title;
const state = post.state;
const category = post.category;
const description = post.description;
if (!req.files)
return res.status(400).send('No files were uploaded.');
const file = req.files.uploaded_image;
var img_name = file.name;
if (file.mimetype == "image/jpeg" || file.mimetype == "image/png" || file.mimetype == "image/gif") {
file.mv('public/imgs/uploads/' + file.name, function (err) {
var sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES (?,?,?,?,?,?)";
var query = con.query(sql, [username, title, state, category, img_name, description], function (err) {
console.log(err)
if (!err) {
res.redirect('show/' + username + '/' + category);
}
else {
message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
res.render('new.ejs', { message: message });
}
});
});
}
}
else {
res.render('new');
}
};
exports.show = function (req, res) {
let message = '';
con.query('SELECT * FROM nt_data WHERE username=? AND category=?', [req.params.username, req.params.category], (err, result) => {
console.log(err)
if (result.length <= 0) {
message = "show not found!";
res.render('show.ejs', { data: result, message: message });
}
else {
res.redirect('places/' + username);
}
});
res.render('show');
};
here's a part of my index.js code
app.get('/new', loginRequired, routes.new);
app.post('/', loginRequired, routes.new);
app.get('/show/:username/:category', loginRequired, routes.show);
app.post('/', loginRequired, routes.show);
app.get('/places/:username', loginRequired, routes.show);
error
ReferenceError: data is not defined
ReferenceError: username is not defined
In show function, you need to get username like this:
req.params.username
And for data I don't see where do you reference it, in witch line to do get an error?
exports.show = function (req, res) {
let message = '';
con.query('SELECT * FROM nt_data WHERE username=? AND category=?', [req.params.username, req.params.category], (err, result) => {
console.log(err)
if (result.length <= 0) {
message = "show not found!";
res.render('show.ejs', { data: result, message: message });
}
else {
res.redirect('places/' + req.params.username); // Change here
}
});
res.render('show');
};
var express = require('express');
var search = express.Router();
search.get('/', function(req, res, next) {
console.log('1');
dbCall(function(error, result) {
if (error) {
res.status(404).json();
} else {
res.json(result);
}
});
console.log('last');
next();
});
var dbCall = function(callback) {
var couchbase = require('couchbase');
var cluster = new couchbase.Cluster('couchbase://127.0.0.1');
var bucket = cluster.openBucket('default');
var doc;
var ViewQuery = couchbase.ViewQuery;
var query = ViewQuery.from('dev_test', 'allData');
bucket.query(query, function(err, viewResults) {
if (err) {
callback(err, null);
} else {
console.log('inqueryCall');
var results = viewResults;
callback(null, results);
console.log(results);
}
});
};
module.exports = search;
Here's the error that I get is :
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
Can someone please explain the issue here(not just the solution)?
I've added console.log and the issue here is that the couchbase call to async
Remove next() call, that is causing this error. next() is used in middleware to pass the flow to next middleware or endpoint/route
search.get('/', function(req, res, next) {
dbCall(function(error, result) {
if (error) {
res.status(404).json();
} else {
res.json(result);
}
});
});
I am trying to inject a session value into the request so i can use it on different situation on my app. What i am doing is calling a function by giving the id to search for a user into database and return me the name of that specific user. The issue i am facing is when i try to declare the session, it looks like is not working or the callback is not letting this new value out.
Let me show you my code example for an better idea:
The middleware
var express = require('express');
var session = require('express-session');
var router = express.Router();
var userSession = require('../../helpers/user/userSession');
router.use(function(req, res, next){
if (req.method == "GET") {
if (!req.user) {
req.session.username = '';
}else{
var sess = userSession.findUser(req.user, function(err, user){
if (user) {
console.log(user); //It contains the value i need
req.session.username = user; // Supposed to inject the user value to the username session variable.
};
console.log(req.session.username); //it works until here, out of this function not anymore.
});
console.log(req.session.username); //the req.session.username is empty now
};
return next();
}else{
return next();
}
});
Check if user exist
var mongoose = require('mongoose');
var User = mongoose.model('database')
module.exports = {
findUser: function(user, callback){
User.findOne({ 'unq_id' : user }, function(err, user){
if (err) {
console.log('Error: ' +err);
return callback(err, false);
};
if (user) {
//console.log(user);
return callback(null, user.user_collection.firstname);
}else{
return callback(err, false);
};
});
}
}
One idea is to give to that sess variable the value of user, but it appears very difficult since is asynchronous call. I am sure some of might have run into this issue.
How can i get around this? any suggestion will be much appreciated.
How about this?
router.use(function(req, res, next){
if (req.method == "GET") {
if (!req.user) {
req.session.username = '';
next();
} else {
userSession.findUser(req.user, function(err, user){
if (user) {
req.session.username = user;
};
next();
});
}
} else {
next();
}
});
That way it won't go to the next middleware until after the username has been retrieved.
I have tried to pass a variable from my index.html to the database(maildata.js) through app.js(server) and get the corresponding data
I am able to get the data from the database but couldnt send that back to the server(app.js)
app.js
var express = require('express');
var maildata= require('./maildata');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
});
app.get('/', function(request, response){
response.sendfile(__dirname + '/mailbox.html');
});
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
var result=maildata.getMailData(input);
response.send(result);
response.end();
});
app.listen(8888);
console.log('Server is running on port 8888');
maildata.js
exports.getMailData=function(data,response) {
var stop_name= data;
connection.query("select stop_name,stop_comment from stoplist where stop_name= '"+stop_name+"' limit 1",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString1= JSON.stringify(rows);
connection.query("select mailbox_sequence_no from stoplist where stop_name= '"+stop_name+"'",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString2 = JSON.stringify(rows);
connection.query("select party_head from stoplist where stop_name= '"+stop_name+"'", function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString3 = JSON.stringify(rows);
var result=jsonString1+'/'+jsonString2+'/'+jsonString3;
response.send(result);
}
});
}
});
}
});
}
Thanks in Advance
How about sending response along when you call the function?
var result=maildata.getMailData(input); // something missing here
Your getMailData function expects two arguments:
exports.getMailData=function(data,response) { ... }
but you give it only one:
var result=maildata.getMailData(input);
Which makes the value of the response argument undefined.
Here is what you should do:
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
maildata.getMailData(input, response);
});
and let maildata.getMailData handle the response sending, as you did in response.send(result);
I have used asynchronous callback method in my app.js.
I got the result
var result=maildata.getMailData(input,response,function(data){
response.send(data);
response.end();
});
Thanks all
I am using express session to login user.
Middleware:
var requireLogin = function (req, res, next) {
if (req.session.user) {
next();
} else {
res.redirect('/');
}
}
Route:
app.post('/login', requireLogin, routes.login);
exports.login = function (req, res) {
var query = {username:req.body.username, password:req.body.password};
User.find(query, function (err, data) {
if (data) {
req.session.user = data;
console.log(data);
res.redirect('/home');
} else {
console.log(err);
res.redirect('/');
}
});
};
When I enter a wrong username and password, it still redirect to home, but the data is null.
find returns an array of match results and findOne returns a matching document.
I guess findOne is appropriate for this case.
app.post('/login', requireLogin, routes.login);
exports.login = function (req, res) {
var query = {username:req.body.username, password:req.body.password};
User.findOne(query, function (err, data) {
if (data && !err) {
req.session.user = data;
console.log(data);
res.redirect('/home');
} else {
console.log(err);
res.redirect('/');
}
});
};
Because find returns an array of results, if (data) will still evaluate to true even if it's empty.
findOne would be more appropriate, because you are looking for just the one user with that unique username/password combination. This way if (data) will only evaluate to true if a matching User if found.
User.findOne(query, function (err, data) {
if (err) {
// the username/password could be valid (or not),
// but there's no way to tell because there was some server error
console.log(err);
res.redirect('/');
} else if (data) {
// a user was found that matched the query
req.session.user = data;
console.log(data);
res.redirect('/home');
} else {
// there is no User that matches the query
res.redirect('/');
}
});