精通
英语
和
开源
,
擅长
开发
与
培训
,
胸怀四海
第一信赖
本文介绍了使用Node.js和Express Framework开发的示例应用程序,并使用MongoDB作为后端。
应用程序中使用了以下技术:
Express框架:Express是一个极小而灵活的Node.js Web应用程序框架,为Web和移动应用程序提供了一组强大的功能。
Node.js: Node.js是用于服务器端和网络应用程序的开源跨平台运行时环境。Node.js应用程序是用JavaScript编写的,可以在OS X,Microsoft Windows,Linux和FreeBSD上的 Node.js运行时中运行。
MongoDB:MongoDB是一个使用面向文档的数据模型开源数据库。MongoDB是2000年代中期NoSQL旗帜下出现的几种数据库类型之一。MongoDB不是在关系数据库中使用表和行,而是建立在集合和文档的架构上。
资源:
安装节点包管理器(npm):
http://nodejs.org/download/
设置Visual Studio for Express Framework模板:
https://nodejstools.codeplex.com/wikipage?title=Installation
MongoDb相关资源 - 安装,运行,数据库查询:
http://docs.mongodb.org/manual/
Jade模板引擎:
http://jade-lang.com/tutorial/
如果已成功安装Visual Studio的nodejs工具,则可以创建Express Application,如下所示:
我们讲解应用程序中使用的3个主要元素:
包含相应视图的JavaScript逻辑(jquery,验证器)。
全球JavaScript,样式表,字体。
数据库管理器,服务器端代码的实用功能。例如:发送邮件实用程序。
包含Jade视图。
包含应用程序中使用的库。
先启动MongoDb守护程序/服务器,然后运行该项目。
这是应用程序的配置。它指定了应用程序所需的依赖关系(modules / libraries),如果npm install在Visual Studio的Package Manager控制台中运行' '命令时它不存在,那么它将被安装。
{ "name": "ExpressApp2", "version": "0.0.0", "description": "ExpressApp2", "main": "app.js", "author": { "name": "tushar.gupta", "email": "" }, "dependencies": { "emailjs": "^0.3.3", "express": "3.4.4", "jade": "*", "stylus": "*", "moment": "^1.7.2", "mongodb": "*" } }
该文件设置node.js应用程序的初始化参数。
/** * Module dependencies. */ var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); // all environments //app.set('port', process.env.PORT || 3000); app.set('port', 3000); app.set('views', path.join(__dirname, '/app/server/views')); app.set('view engine', 'jade'); app.locals.pretty = true; //app.use(express.favicon()); //app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(express.session({ secret: 'super-duper-secret-secret' })); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(require('stylus').middleware(path.join(__dirname, '/app/public'))); app.use(express.static(path.join(__dirname, '/app/public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } require('./app/server/router')(app); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
该文件充当控制器并响应客户端的请求。它设置视图的数据(从服务/数据库)并发送响应。
//Get Function app.get('/', function (req, res) { // check if the user's credentials are saved in a cookie // if (req.cookies.user == undefined || req.cookies.pass == undefined) { res.render('login', { title: 'IB-Wall - Please Login To Your Account' }); } else { // attempt automatic login // AM.autoLogin(req.cookies.user, req.cookies.pass, function (o) { if (o != null) { req.session.user = o; res.redirect('/user/' + req.cookies.user); } else { res.render('login', { title: 'IB-Wall - Please Login To Your Account' }); } }); } }); //Post Function app.post('/', function (req, res) { AM.manualLogin(req.param('user'), req.param('pass'), function (e, o) { if (!o) { res.send(e, 400); } else { req.session.user = o; res.cookie('user', o.user, { maxAge: 900000 }); res.cookie('pass', o.pass, { maxAge: 900000 }); res.send(o, 200); console.log('user login and redirecting to home'); } }); }); //user wall page //Parameters from URL app.get('/user/:username', function (req, res) { if (req.session.user == null) { res.redirect('/'); } else { var uName = req.param('username'); AM.getAllRecords(function (e, accounts) { AM.getUserByUname(uName, function (e, onWQallOfuser) { AM.getPostsForUser(onWQallOfuser, function (e, userPosts) { var uPosts = []; uPosts = userPosts; res.render('index', { title : 'Welcome to IB-Wall', udata : req.session.user, wallUserData: onWQallOfuser, accounts: accounts, userPosts: uPosts }); }); }); }); } }); //Destroy Cookies app.post('/logoutuser', function (req, res) { if (req.param('logout') == 'true') { res.clearCookie('user'); res.clearCookie('pass'); req.session.destroy(function (e) { res.send('ok', 200); }); } });
这是将HTML呈现给客户端的查看文件。
您可以使用许多在线转换器将HTML代码转换为Jade代码。
您可以从在线资源中更多地了解Jade。
Jade 遵循缩进风格来组合元素。
extends walllayout block content include userdetails .wrapper .box .row.row-offcanvas.row-offcanvas-left // sidebar #sidebar.column.col-sm-2.col-xs-1.sidebar-offcanvas ul.nav li a.visible-xs.text-center(href='#', data-toggle='offcanvas') i.glyphicon.glyphicon-chevron-right ul#lg-menu.nav.hidden-xs each account in accounts li.active a(href='http://www.codeproject.com/user/#{account.user}') img.img-circle(src='http://www.codeproject.com/placehold.it/150x150', width='25px', height='25px') | #{account.name}
从服务器变量和设置中获取数据以供在视图中使用。
// preset form values if we receive a userdata object // //variables are declared by using '-' sign //Data from server can be get just by using the same variable name as declared on server end. - user = typeof(udata) != 'undefined' ? udata : { } - wallUser = typeof(wallUserData) != 'undefined' ? wallUserData : { } // store the userId on the client side in a hidden input field // input(type='hidden', value= user._id)#userId input(type='hidden', value= wallUser._id)#wallUserId input(type='hidden', value= user.name)#LoginUserFullName input(type='hidden', value= wallUser.name)#wallUserFullName // display form errors in a custom modal window // include modals/form-errors
extends walllayout
block content
include userdetails
script(src='http://www.codeproject.com/vendor/javascripts/scripts.js')
head title= title link(rel='stylesheet', href='http://www.codeproject.com/vendor/stylesheets/bootstrap_wall.min.css')
此文件负责以下操作:
var crypto = require('crypto'); var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var moment = require('moment'); var dbPort = 27017; var dbHost = 'localhost'; //var dbName = 'node-login'; var dbName = 'manthandb-oaapt'; /* establish the database connection */ var db = new MongoDB(dbName, new Server(dbHost, dbPort, { auto_reconnect: true }), { w: 1 }); db.open(function (e, d) { if (e) { console.log(e); } else { console.log('connected to database :: ' + dbName); } }); var accounts = db.collection('accounts'); var posts = db.collection('posts'); var likes = db.collection('userlikes');
//Insert exports.addNewPost = function (data, callback) { data.createdDate = moment().format('MMMM Do YYYY, h:mm:ss a'); posts.insert(data, function (e, postAdded) { if (!e) { callback(null, postAdded); } }); } //Select 1 exports.autoLogin = function (user, pass, callback) { accounts.findOne({ user: user }, function (e, o) { if (o) { o.pass == pass ? callback(o) : callback(null); } else { callback(null); } }); } //Select Multiple exports.getAllRecords = function (callback) { accounts.find().toArray( function (e, res) { if (e) callback(e) else callback(null, res) }); }; //Delete exports.deleteAccount = function (id, callback) { accounts.remove({ _id: getObjectId(id) }, callback); }