我几乎是网络开发的初学者。我正在制作一个非常基本的网页用于登录身份验证。我想做的就是从数据库(mongoose)检查登录页面上的用户凭据(用户名和密码),如果正确则重定向到下一页(MainPage)。
Login.ejs (.html) 文件
<html>
<head>
<title>Login</title>
</head>
<body>
<form id="form_Login" action="/MainPage" method="post">
<input id="txt_username" type="text" required>
<br><input id="txt_password" type="password" required>
<br><input type="submit" value="Login">
</form>
</body>
</html>
app.js 文件
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema ({
username : String,
password : String
});
mongoose.model('User',User);
mongoose.connect('mongodb://localhost:27017/MyDB');
app.set('view engine', 'ejs');
app.get('/',function(req, res) {
res.render('LoginPage');
});
app.get('/MainPage',function(req, res) {
res.render('MainPage');
});
app.post('/MainPage', function(req, res) {
// new code should come over here
res.redirect('/MainPage');
});
app.get('*', function(req, res) {
res.send('Bad Route!');
});
var server = app.listen(3000, function() {
console.log('listening on port 3000.');
});
如有任何帮助,我们将不胜感激。
最佳答案
我建议您使用passport.js图书馆为此。 它不仅为您提供了创建本地身份验证的好方法,您还可以稍后集成 google、facebook 和 twitter(或任何 oAuth)社交身份验证方法。
您可以阅读应该为您提供良好起点的文档,或以下示例之一:
- http://passportjs.org/docs
- http://mherman.org/blog/2013/11/11/user-authentication-with-passport-dot-js/#.VYAS0PlViko
- http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4/#.VYAS0vlViko
- https://scotch.io/tutorials/easy-node-authentication-setup-and-local (我以前用过这个)
我建议您首先使用护照本地方案,这将满足您的需求。 https://github.com/jaredhanson/passport-local
关于javascript - Node.js 和 MongoDB (mongoose) 中的登录表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30867209/