我有一个注册表单,我需要在存在用户名或电子邮件时发送错误消息:
nodejs代码:
app.post('/register', function(req, res) {
var entity = _.pick(req.body, 'password', 'fullName', 'email', 'userName', 'phone', 'companyName', 'companyWebsite');
// hash password
entity.password = bcrypt.hashSync(entity.password, config.SALT_WORK_FACTOR);
async.waterfall([
function(cb) {
if(entity.userName) {
userService.findByUsername(entity.userName, function(err, user) {
if(err) {
cb(err);
} else if(user) {
cb(new errors.ValidationError('Cannot create user, userName already exists', httpStatus.BAD_REQUEST));
} else {
cb();
}
});
} else {
cb();
}
},
function(cb) {
if(entity.email) {
userService.findByEmail(entity.email, function(err, user) {
if(err) {
cb(err);
} else if(user) {
cb(new errors.ValidationError('Cannot create user, email already exists', httpStatus.BAD_REQUEST));
} else {
cb();
}
});
} else {
cb();
}
},
function(cb) {
crud.create(entity, cb);
},
], function(err, createdEntity) {
data = {
statusCode: httpStatus.CREATED,
content: createdEntity
};
if(err)
{
res.render('register', {user : undefined, success :true,successs :true});
}
else{
res.render('login', {user : undefined, success :true});
}
});
});
我的ejs文件代码是:
<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<strong>oops!</strong>Cannot create user, username already exists
</div>
<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<strong>oops!</strong>Cannot create user, email already exists
</div>
如何将消息错误传递或发送到ejs文件..消息错误显示在if(user):cb(new errors.ValidationError('Cannot create user, userName already exists', httpStatus.BAD_REQUEST));
答案 0 :(得分:0)
您可以使用
打印从服务器端部件传递到ejs的数据 <%=%>
例如:&lt;%= user%&gt;将打印用户。
当错误的对象存在时,将它作为第三个对象发送到ejs文件并以相同的方式读取它。
if(err){
res.render('register', {user : undefined, success :true,successs :true,error: err});
}
并在视图中
<%if(typeof error == "undefined"){%>
//Show some HTML here
<% } else { %>
//Show other html when you send error obejct sent
<%= error.message%> //For Example
<%}%>