Reputation: 3
const con = require('./../connection');
exports.getProfile = async function(req,res){
var user_id = req.session.user_id;
var userList = '';
var id = req.params.id ? req.params.id : '';
if(!id)
{
id = user_id;
}
await con.query('select * from users where id = ?',[id],function(error,results,fields){
res.render('profile',{
userResult: results[0],
});
});
};
<input type="text" name="f_name" data-required="1" value="<%= userResult.first_name %>" class="form-control">
getting correct response on web but getting error in console Cannot read property 'first name' of undefined nodejs
Upvotes: 0
Views: 78
Reputation: 30675
If you wish to access the data outside of the module you'll need to do something like so:
exports.getProfile = async function(req,res){
var user_id = req.session.user_id;
var userList = '';
var id = req.params.id ? req.params.id : '';
if(!id)
{
id = user_id;
}
return new Promise((resolve, reject) => {
con.query('select * from users where id = ?', [id], function(error, results, fields) {
if (error) {
reject(error);
} else {
console.log("First name: ", results[0].first_name);
res.render('profile',{
userResult: results[0],
});
resolve(results[0]);
}
});
})
};
And then in your importing script:
const { getProfile } = require('./get-profile');
async function testGetProfile() {
let profile = await getProfile(req, res);
console.log("Profile: First name: ", profile.first_name);
}
// Pull req, res from relevant route..
testGetProfile(req, res);
Upvotes: 0
Reputation: 179
I think you have a synchronization issue there.
You're trying to access userResult before the function callback ends.
I don't know what you're trying to accomplish there but the value you're trying to access will be available here:
await con.query('select * from users where id = ?',[id],function(error,results,fields){
// HERE YOU CAN ACCESS TO results[0]
res.render('profile',{
userResult: results[0],
});
});
Upvotes: 1