gpt4 book ai didi

javascript - 快速验证器总是无效

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:15 26 4
gpt4 key购买 nike

我正在最新版本的 nodejsexpress 上构建一个项目,我有一个基本的站点设置,我只是想让用户身份验证工作(从 this 学习) )

但无论我做什么,我都无法让express-validator来验证它永远是无效的

validator deprecated you tried to validate a undefined but this library (validator.js) validates strings only. Please update your code as this will be an error soon. node_modules/express-validator/lib/express_validator.js:338:41

这是我遇到的唯一错误,但我不知道该怎么做,因为一切似乎都与 github 文档匹配

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
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 expressValidator = require('express-validator');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;


var routes = 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');

// Handle File Uploads
var multer = require('multer');
var upload = multer({ dest: './uploads' });

// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
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 handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;

路由/user.js

var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
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;

// Check for Image Field
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 Message
req.flash('success','You are now registered and may log in');

res.location('/');
res.redirect('/');
}
});

passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});

passport.use(new LocalStrategy(
function(username, password, done){
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
console.log('Unknown User');
return done(null, false,{message: 'Unknown User'});
}

User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
console.log('Invalid Password');
return done(null, false, {message:'Invalid Password'});
}
});
});
}
));

router.post('/login', passport.authenticate('local',{failureRedirect:'/users/login', failureFlash:'Invalid username or password'}), function(req, res){
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
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='Username')
.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')

最佳答案

isEmpty() 代替 .notEmpty() 检查

来源:ValidateJS

isEmpty : validate.isEmpty(value)
Check if the given value is non empty. The following value are considered empty:

null
undefined
Empty strings
Whitespace only strings
Empty arrays
Empty objects

关于javascript - 快速验证器总是无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36197082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com