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">
在Web上获得正确的响应,但在控制台中出现错误无法读取未定义的Node.js的属性“名字”
答案 0 :(得分:1)
我认为您那里存在同步问题。
您正在尝试在函数回调结束之前访问userResult。
我不知道您要在此处完成什么,但是您要访问的值将在此处提供:
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],
});
});
答案 1 :(得分:0)
如果您希望访问模块外部的数据,则需要执行以下操作:
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]);
}
});
})
};
然后在您的导入脚本中:
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);