问题描述
我已在views/employee/login.hbs中的应用程序页面中添加了登录和注册功能.当我输入注册详细信息(电子邮件,用户名,密码和conf密码)时,我点击了注册按钮,希望可以重定向到views/employee/home.hbs页面.但是,当我完成此操作后,我的MongoDB Compass社区数据库收到了我已成功输入的注册详细信息,但我的浏览器显示无法访问该站点",并且当应为URL时,URL为"localhost:3000/employee/employee/login"本地主机:3000/员工/家庭".我在下面的代码中添加了将要使用的代码.我还添加了下面的文件夹和文件结构,并打开了文件夹以显示此显示.我是Node js的新手,所以对不起,这很简单.
I have added login and registration features to a page in my application in views/employee/login.hbs. When I enter in registration details (email, username, password and conf password), I hit the register button to hopefully be redirected to the views/employee/home.hbs page. However, when I complete this action my MongoDB Compass Community database receives the registration details that I have entered successfully but my browser states 'The site cannot be reached' and URL is "localhost:3000/employee/employee/login" when it should be "localhost:3000/employee/home". I have added in the code below that would be in use. I have also added the the folder and file structure below with the folders open to show this display. I am new to Node js so I am sorry if this is an easy fix.
我尝试在控制器文件或"form action ="/employee/login方法中的" router.post('/employee/login',function(req,res,next){)中更改路由="post"转到其他方式,但是对于我使用的方式,出现错误-无法POST/employee/login,或类似的错误(无法POST/等)
I have tried changing the routes in the "router.post('/employee/login', function (req, res, next) {" in the controller file or the "form action="/employee/login" method="post" to other ways but for the ones I used got an error of - Cannot POST /employee/login, or similar (Cannot POST / etc)
controllers/employeeController.js
controllers/employeeController.js
router.get('/home', (req, res) => {
res.render('employee/home', {layout: 'main.hbs'});
});
router.get('/login', (req, res) => {
res.render('employee/login', {layout: 'main.hbs'});
});
//POST route for updating data
router.post('/employee/login', function (req, res, next) {
// confirm that user typed same password twice
if (req.body.password !== req.body.passwordConf) {
var err = new Error('Passwords do not match.');
err.status = 400;
res.send("passwords dont match");
return next(err);
}
if (req.body.email &&
req.body.username &&
req.body.password &&
req.body.passwordConf) {
var userData = {
email: req.body.email,
username: req.body.username,
password: req.body.password,
}
User.create(userData, function (error, user) {
if (error) {
return next(error);
} else {
req.session.userId = user._id;
return res.redirect('employee/home');
}
});
} else if (req.body.logemail && req.body.logpassword) {
User.authenticate(req.body.logemail, req.body.logpassword, function (error, user) {
if (error || !user) {
var err = new Error('Wrong email or password.');
err.status = 401;
return next(err);
} else {
req.session.userId = user._id;
return res.redirect('employee/home');
}
});
} else {
var err = new Error('All fields required.');
err.status = 400;
return next(err);
}
})
// GET for logout logout
router.get('/logout', function (req, res, next) {
if (req.session) {
// delete session object
req.session.destroy(function (err) {
if (err) {
return next(err);
} else {
return res.redirect('employee/login');
}
});
}
});
module.exports = router;
models/user.js(应该很好,因为数据库可以接收数据,但为进一步的上下文而显示)
models/user.js (should be fine since database recieves data but shown for further context)
var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
trim: true
},
username: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
required: true,
}
});
//authenticate input against database
UserSchema.statics.authenticate = function (email, password, callback) {
User.findOne({ email: email })
.exec(function (err, user) {
if (err) {
return callback(err)
} else if (!user) {
var err = new Error('User not found.');
err.status = 401;
return callback(err);
}
bcrypt.compare(password, user.password, function (err, result) {
if (result === true) {
return callback(null, user);
} else {
return callback();
}
})
});
}
//hashing a password before saving it to the database
UserSchema.pre('save', function (next) {
var user = this;
bcrypt.hash(user.password, 10, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
})
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
server.js
server.js
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/testForAuth', { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false }, (err) => {
if (!err) { console.log('MongoDB Connection Succeeded.') }
else { console.log('Error in DB connection : ' + err) }
});
var db = mongoose.connection;
//handle mongo error
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
});
//use sessions for tracking logins
app.use(session({
secret: 'work hard',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
const employeeController = require('./controllers/employeeController');
var app = express();
//setting up morgan middleware
app.use(logger('dev'));
app.use(bodyparser.urlencoded({
extended: false
}));
app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainLayout', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine', 'hbs');
//serving blank favicon to keep from throwing 404 errors
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
//setting up static path for serving static files
app.use(express.static(path.join(__dirname, 'public')));
//Bringing in the routes
const index = require('./routes/index');
const api = require('./routes/api');
app.use('/', index);
app.use('/api', api);
app.listen(3000, () => {
console.log('Express server started at port : 3000');
});
app.use('/employee', employeeController.router);
views/employee/login.hbs(把手)
views/employee/login.hbs (handlebars)
<h3>Login</h3>
<div class="login-form">
<form action="employee/login" method="post">
<input type="text" name="logemail" placeholder="E-mail" required="">
<input type="password" name="logpassword" placeholder="Password" required="">
<div class="tp">
<input type="submit" value="LOGIN NOW">
</div>
</form>
</div>
</div>
</div>
<div class="agile">
<div class="signin-form profile">
<h3>Register</h3>
<div class="login-form">
<form id="login2" action="employee/login" method="post" onsubmit="event.preventDefault(); validateMyForm();">
<input type="text" name="email" placeholder="E-mail" required="">
<input type="text" name="username" placeholder="Username" required="">
<input type="password" name="password" placeholder="Password" id="password" required="" >
<input type="password" name="passwordConf" placeholder="Confirm Password" id="password_conf" required="">
<input type="submit" value="REGISTER">
</form>
</div>
<p><a href="#"> By clicking register, I agree to your terms</a></p>
</div>
</div>
<div class="clear"></div>
</div>
<script type="text/javascript">
var passWordField = document.getElementById('password')
var passWordConfirmField = document.getElementById('password_conf')
var form = document.getElementById('login2')
function validateMyForm(){
if(passWordField.value != passWordConfirmField.value){
alert("Passwords do not match. Please try again.");
} else {
form.submit()
}
}
</script>
</body>
</html>
推荐答案
使用
req.session.userId = user._id;
此外,使用res.redirect进行任何更改
Also, change anything with res.redirect as such
return res.redirect('employee/home');
按原样渲染
return res.render('employee/home');
这篇关于节点JS表单提交TypeError:无法设置未定义的属性'userId'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!