验证 express js 中的表单字段时出现错误消息的问题
Posted
技术标签:
【中文标题】验证 express js 中的表单字段时出现错误消息的问题【英文标题】:issues with error messages while validating the form field in express js 【发布时间】:2017-10-05 07:26:26 【问题描述】:如果出现任何验证错误,我想在同一个翡翠页面(即 register.jade)中显示适当的错误消息。如果没有,那么我想在模式对象的帮助下成功存储数据并返回我的主页.但是目前,即使输入正确,我也会收到所有错误消息。
我正在使用 Express+Node+Mongodb+Mongoose。
我可以知道如何实现它。
我正在关注的相关(12:55 分钟)视频是 - https://www.youtube.com/watch?v=jeiP4jN1mfs&list=PLNiY_2deiFolObKp8sav6TmxnnjVFuwqu&index=16
这是我的代码 -
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session=require('express-session');
var passport=require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer( dest: './uploads' );
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: false ));
//Handle Express Sessions
app.use(session(
secret:'secret',
saveUninitialized:true,
resave:true
));
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Validator
app.use(expressValidator(
errorFormatter: function(param, msg, value)
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length)
formParam += '[' + namespace.shift() + ']';
return
param : formParam,
msg : msg,
value : value
;
));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next)
res.locals.messages = require('express-messages')(req, res);
next();
);
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next)
var err = new Error('Not Found');
err.status = 404;
next(err);
);
// error handler
app.use(function(err, req, res, next)
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : ;
// render the error page
res.status(err.status || 500);
res.render('error');
);
module.exports = app;
users.js(在路由文件夹内)
var express = require('express');
var router = express.Router();
var User = require('../models/user');
/* GET users listing. */
router.get('/', function(req, res, next)
res.send('respond with a resource');
);
router.get('/register', function(req, res, next)
res.render('register',
'title': 'Register'
);
);
router.get('/login', function(req, res, next)
res.render('login',
'title': 'Login'
);
);
router.post('/register',function(req,res,next)
//Get form values
var name=req.body.name;
var email=req.body.email;
var username=req.body.username;
var password=req.body.password;
var password2=req.body.password2;
if(req.files && req.files.profileimage)
console.log('Uploading FIle...');
//FIle Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
else
// Set a Default Image
var profileImageName = 'noimage.png';
//Form Validation
req.checkBody('name','Name field is required').notEmpty();
req.checkBody('email','Email field is required').notEmpty();
req.checkBody('email','Email not valid').isEmail();
req.checkBody('username','Username field is required').notEmpty();
req.checkBody('password','password field is required').notEmpty();
req.checkBody('password2','passwords do not match').equals(req.body.password);
//Check for errors
var errors = req.validationErrors();
if(errors)
res.render('register',
errors:errors,
name:name,
email:email,
username:username,
password:password,
password2:password2
);
else
var newUser = new User(
name:name,
email:email,
username:username,
password:password,
profileimage:profileImageName
);
//Create User
User.createUser(newUser, function(err,user)
if(err) throw err;
console.log(user);
);
//Success Messsage
req.flash('success','You are now registered and may log in');
res.location('/');
res.redirect('/');
);
module.exports = router;
views文件夹中的register.jade
extends layout
block content
h1 Register
p Please Register using the form below
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #error.msg
form(method='post',action='/users/register',enctype='multipart/form-data')
.form-group
label Name
input.form-control(name='name', type='text',placeholder='Enter Name')
.form-group
label Email
input.form-control(name='email', type='email',placeholder='Enter Email')
.form-group
label Username
input.form-control(name='username', type='text',placeholder='User Name')
.form-group
label Password
input.form-control(name='password', type='password',placeholder='Enter Password')
.form-group
label Confirm Password
input.form-control(name='password2', type='password',placeholder='Confirm Password')
.form-group
label Profile Image
input.form-control(name='profileimage', type='file')
input.btn.btn-default(name='submit',type='submit',value='Register')
截图:
enter image description here
【问题讨论】:
【参考方案1】:来自 express github repo req.validationErrors([mapped]) 列在已弃用的 API 下 我引用他们 “以下方法已弃用。 虽然它们工作,但它们的 API 不灵活,如果与最前沿的 req.getValidationResult() 相比,有时会返回奇怪的结果。
此外,这些方法可能会在未来的版本中被移除。”
所以你应该改用这个方法:-
req.getValidationResult()
.then(function(result)
console.log(result.array());
);
来源:-https://github.com/ctavan/express-validator#usage
【讨论】:
你能帮我提供更具体的答案吗? @Fadi Abo Msalam 在文件 users.js(在路由文件夹内)替换 var errors = req.validationErrors();使用 req.getValidationResult() .then(function(result) you else -no error from validation - ) .catch(function(error) your code for handling error );这够清楚吗 这很清楚。非常感谢@Fadi Abo Msalam。 没问题,我的朋友,但如果解决方案有效,请将问题标记为已解决,以帮助他人。问候 实际上另一种方式现在不起作用。错误消息没有显示。我的 users.js 代码 sn-p 如下:以上是关于验证 express js 中的表单字段时出现错误消息的问题的主要内容,如果未能解决你的问题,请参考以下文章
尝试在 Heroku 上部署 Node.js/Express/Socket.io 应用程序时出现应用程序错误