在将其标记为重复之前,请理解我所查看的答案都不足以解决我的代码问题。我正在尝试修复 Web 应用程序中的错误,该应用程序正在将文件从 Internet 上传到家庭服务器。我目前正在研究基本的用户身份验证系统。当我尝试在主页上提交登录表单时,我被重定向到一个错误页面,其中一部分显示“无法读取未定义的属性'用户名'”。此消息也出现在控制台中。发生了什么,我该如何解决?该错误将我引导至家庭控制器的第 8 行,“username = req.body.username”。应用程序.js
var LocalStrategy = require('passport-local').Strategy;
var flash = require("connect-flash");
var passport = require("passport");
var session = require("express-session");
var expressValidator = require("express-validator");
var mongoose = require("mongoose");
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
var bodyParser = require('body-parser');
var ejs = require('ejs');
var routes = require('./server/routes');
routes(app);
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cookieParser());
mongoose.connect("mongodb://localhost:27017/users");
app.listen(app.get('port'), function(){
console.log("server started");
});
var db = mongoose.connection;
app.use(session({
secret: 'yVVma9ga',
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
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(flash());
app.use(function(req,res,next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash("error");
next();
});
/server/routes.js
var express = require("express");
var home = require('../controllers/home');
var client = require('../controllers/client');
module.exports = function(app) {
var router = express.Router();
app.use('/', router);
router.get('/', home.index);
router.get('/client', client.home);
router.post('/', home.login);
}
控制器/home.js
module.exports = {
index: function(req, res){
res.render("home");
},
login: function(req, res){
var username = req.body.username;
var password = req.body.password;
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
var errors = req.validationErrors();
if(errors){
console.log("YES");
}else{
console.log("NO");
};
}
}
/views/home.ejs(部分只是基本的html)
<% include partials/header %>
<p>Welcome to your personal server!</p>
<p>Login!</p>
<form method="post" action = "/">
<input placeholder="Username" type="text" name="username">
<input placeholder="Password" type="password" name="password">
<input type="submit" value="Submit">
</form>
<% include partials/footer %>