请按照以下简单步骤来学习如何使用Node.js和MongoDB创建登录表单。登录表单允许用户使用注册表单创建帐户后登录网站。
模块安装:
$ npm install ejs
嵌入式javaScript可让你使用纯JavaScript生成HTML标记。
$ npm install express --save
Express是Node的模块框架, 可用于应用程序。
$ npm install mongoose
Mongoose是用于MongoDB和Node.js的对象数据建模(ODM)库。它管理数据之间的关系, 提供架构验证, 并用于在代码中的对象和MongoDB中的这些对象的表示之间进行转换。
$ npm install body-parser --save
Body-parser允许express读取主体, 然后将其解析为我们可以理解的JSON对象。
npm install express-session --save
Express.js使用cookie来存储会话ID。
npm install passport passport-local --save
npm install passport-local-mongoose --save
Passport是Node的身份验证中间件。 js。 Passport极其灵活和模块化, 可以毫不费力地放入任何基于Express的Web应用程序中。一套全面的策略支持使用用户名和密码, Facebook, Twitter等进行身份验证。
文件名:app.js
var express = require( "express" ), mongoose = require( "mongoose" ), passport = require( "passport" ), bodyParser = require( "body-parser" ), LocalStrategy = require( "passport-local" ), passportLocalMongoose =
require( "passport-local-mongoose" ), User = require( "./models/user" );
mongoose.set( 'useNewUrlParser' , true );
mongoose.set( 'useFindAndModify' , false );
mongoose.set( 'useCreateIndex' , true );
mongoose.set( 'useUnifiedTopology' , true );
mongoose.connect( "mongodb://localhost/auth_demo_app" );
var app = express();
app.set( "view engine" , "ejs" );
app.use(bodyParser.urlencoded({ extended: true }));
app.use(require( "express-session" )({
secret: "Rusty is a dog" , resave: false , saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use( new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//=====================
//ROUTES
//=====================
//Showing home page
app.get( "/" , function (req, res) {
res.render( "home" );
});
//Showing secret page
app.get( "/secret" , isLoggedIn, function (req, res) {
res.render( "secret" );
});
//Showing register form
app.get( "/register" , function (req, res) {
res.render( "register" );
});
//Handling user signup
app.post( "/register" , function (req, res) {
var username = req.body.username
var password = req.body.password
User.register( new User({ username: username }), password, function (err, user) {
if (err) {
console.log(err);
return res.render( "register" );
}
passport.authenticate( "local" )(
req, res, function () {
res.render( "secret" );
});
});
});
//Showing login form
app.get( "/login" , function (req, res) {
res.render( "login" );
});
//Handling user login
app.post( "/login" , passport.authenticate( "local" , {
successRedirect: "/secret" , failureRedirect: "/login"
}), function (req, res) {
});
//Handling user logout
app.get( "/logout" , function (req, res) {
req.logout();
res.redirect( "/" );
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect( "/login" );
}
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log( "Server Has Started!" );
});
档名:home.ejs
<h1>This is home page</h1>
<li><a href = "/register">Sign up!!</a></li>
<li><a href = "/login">Login</a></li>
<li><a href = "/logout">Logout</a></li>
文件名:login.ejs
<h1>login</h1>
<form action = "/login" method = "POST">
<input type = "text" name = "username"
placeholder = "username">
<input type = "password" name = "password"
placeholder = "password">
<button>login</button>
</form>
<h1>This is home page</h1>
<li><a href = "/register">Sign up!!</a></li>
<li><a href = "/login">Login</a></li>
<li><a href = "/logout">Logout</a></li>
文件名:register.ejs
<h1> Sign up form </h1>
<form action = "/register" method = "POST">
<input type = "text" name = "username"
placeholder = "username">
<input type = "password" name = "password"
placeholder = "password">
<button>Submit</button>
</form>
<h1>This is home page</h1>
<li><a href = "/register">Sign up!!</a></li>
<li><a href = "/login">Login</a></li>
<li><a href = "/logout">Logout</a></li>
文件名:secret.ejs
<h1>This is secrect page</h1>
<img src="https://encrypted-tbn0.gstatic.com/
images? q = tbn %3AANd9GcQ5PdxXFw4u3BRG4166i7Nbk
x0VyGGNt0hWc3loNeD7GIL4nbbo& usqp = CAU ">
<h1>This is home page</h1>
<li><a href = "/register">Sign up!!</a></li>
<li><a href = "/login">Login</a></li>
<li><a href = "/logout">Logout</a></li>
运行程序的步骤:
项目结构将如下所示:
并且views目录的内容将如下所示:
Rest文件是在你运行npm init来初始化.json文件之后创建的。
使用以下命令运行index.js文件:
nodemon app.js
或者如果你没有Nodemon安装后可以运行:
node app.js
现在转到浏览器并输入以下URL:
http://localhost:3000/
首先, 你需要注册, 然后只有你可以登录该应用程序。
现在你已经成功注册, 这是登录表单, 如下所示:
此登录表单将带你进入Secret页面, 如下所示:
因此, 这就是使用Node.js和MongoDB创建登录表单的方式。