node. js a simple Blog instance

Source: Internet
Author: User

The original tutorial Https://github.com/nswbmw/N-blog/wiki/_pages the first chapter, due to the version and other reasons, in the original tutorial based on a slight change can be achieved.

Environment:

Win7 Flagship edition 64-bit

node.js:0.10.31

mongodb:2.6.4

express:3.x

Effect: Registration Interface:
Login interface:
Login success:
Post blog:
Publishing success:
Source code: blog/
Blog/package.json

{  "name": "blog",  "version": "0.0.1", "  private": True,  "scripts": {    "start": "Node App.js"  } ,  "dependencies": {    "Express": "3.16.7",    "Ejs": "*", "MongoDB": "*", "Connect-mongo": "*", "Connect-flash" :"*"  }}

Blog/app.js

/** * Module dependencies. */var Express = require (' Express '); var routes = require ('./routes '); var http = require (' http '); var path = require (' path '); var mongostore=require (' Connect-mongo ') (Express), Var settings=require ('./settings '), var flash=require (' Connect-flash '); var app = Express ();//All Environmentsapp.set (' Port ', Process.env.PORT | |); app.set (' views ', Path.join (__dirname, ' views ')), App.set (' View engine ', ' Ejs '); App.use (Flash ()); App.use (Express.favicon ()); App.use ( Express.logger (' Dev '); App.use (Express.bodyparser ()); App.use (Express.methodoverride ()); App.use (Express.static ( Path.join (__dirname, ' public ')); App.use (Express.cookieparser ()); App.use (Express.session ({secret: Settings.cookiesecret, Key:settings.db,//cookie name Cookie: {maxage:1000 * * * * * + * 30},//30 days store:new M Ongostore ({db:settings.db})});//This sentence is written in front of the session will be wrong Why Pinch app.use (app.router);//Development Onlyif (' development ' = = A Pp.get (' env ')) {App.use (Express.errorhandler ());} Routes (app); HTTP. Createserver (APP). Listen (App.get (' Port '), function () {console.log (' Express server listening on port ' + app.get (' Port ') ));});

Blog/settings.js

Module.exports={cookiesecret: ' MyBlog ', DB: ' Blog ', Host: ' localhost '};

Blog/models/blog/models/db.js

var settings=require ('.. /settings '), Db=require (' MongoDB '). Db,connection=require (' MongoDB '). Connection,server=require (' MongoDB '). Server;module.exports=new Db (settings.db,new Server (Settings.host,connection.default_port), {safe:true});

Blog/models/post.js

var MongoDB = require ('./db '); function Post (name, title, post) {this.name = name;  This.title = title; This.post = post;}  Module.exports = post;//Stores an article and its related information Post.prototype.save = function (callback) {var date = new Date (); Store a variety of time formats to facilitate later extension of the var times = {date:date, year:date.getFullYear (), month:date.getFullYear () + "-" + ( Date.getmonth () + 1), day:date.getFullYear () + "-" + (Date.getmonth () + 1) + "-" + date.getdate (), Minute:da Te.getfullyear () + "-" + (Date.getmonth () + 1) + "-" + date.getdate () + "" + date.gethours () + ":" + (Date.getminut ES () < 10? ' 0 ' + date.getminutes (): Date.getminutes ())}//document to be stored in the database var post = {name:this.name, time:time, TI  Tle:this.title, post:this.post};    Open Database Mongodb.open (function (err, db) {if (err) {return callback (ERR);        }//Read posts Collection db.collection (' posts ', function (err, collection) {if (err) {mongodb.close (); Return Callback (ERR);        }//Insert the document into the Posts collection Collection.insert (post, {safe:true}, function (err) {mongodb.close (); if (ERR) {return callback (ERR);//Failed!    Returns ERR} callback (null);//returns ERR as null});  }); });};/ /Read articles and their related information Post.get = function (name, callback) {//Open database Mongodb.open (err, db) {if (err) {return cal    Lback (ERR);        }//Read posts Collection db.collection (' posts ', function (err, collection) {if (err) {mongodb.close ();      Return callback (ERR);      } var query = {};      if (name) {query.name = name;        }//Query the article collection.find based on the query object. Sort ({time:-1}). ToArray (function (err, docs) {        Mongodb.close (); if (ERR) {return callback (ERR);//Failed! Return ERR} callback (null, docs);//success!    Returns the result of the query as an array});  }); });};

Blog/models/user.js
var MongoDB = require ('./db '); function user (user) {this.name = User.Name;  This.password = User.password; This.email = User.email;}; Module.exports = user;//Store user Information User.prototype.save = function (callback) {//user document to be stored in the database var user = {Name:this.name,p  Assword:this.password,email:this.email}; Open Database Mongodb.open (function (err, db) {if (err) {return callback (ERR);//error, return ERR message}//Read users set  Hopewell Db.collection (' Users ', function (err, collection) {if (err) {mongodb.close (); return callback (ERR);//error, Return err Info}//insert user data into the Users collection Collection.insert (user, {safe:true}, function (err, user) {mongodb.cl OSE (); if (err) {return callback (ERR);//error, Return err information}callback (NULL, user[0]);//success!    ERR is null and returns the stored user's document});  }); });};/ /read user Information User.get = function (name, callback) {//Open database Mongodb.open (function (err, db) {if (err) {return callback (ER R);//error, Return ERR information}//Read the Users Collection db.collection (' Users ', function (err, COllection) {if (err) {mongodb.close (); return callback (ERR);//error, return ERR message}//Find user name (name key) value for name a document Collection.findone ({Name:name}, function (err, user) {mongodb.close (); if (err) {return callback (ERR);//Failed! Returns the ERR information}callback (null, user);//success!    Returns the user information of the query});  }); });};
Blog/public/blog/public/stylesheets/style.css

/* Inspired by http://yihui.name/cn/*/*{padding:0;margin:0;} Body{width:600px;margin:2em auto;padding:0 2em;font-size:14px;font-family: "Microsoft Yahei";} P{line-height:24px;margin:1em 0;} Header{padding:.5em 0;border-bottom:1px solid #cccccc;} nav{position:fixed;left:12em;font-family: "Microsoft Yahei"; font-size:1.1em;text-transform:uppercase;width:9em; Text-align:right;} Nav a{display:block;text-decoration:none;padding:.7em 1em;color: #000000;} Nav a:hover{background-color: #ff0000; color: #f9f9f9;-webkit-transition:color. 2s linear;} Article{font-size:16px;padding-top:.5em;} Article A{color: #dd0000; text-decoration:none;} Article A:hover{color: #333333; text-decoration:underline;}. info{font-size:14px;}

Blog/routes/blog/routes/index.js

/* * GET home page. */var crypto = require (' crypto '), User = require ('.. /models/user.js '), Post=require ('. /models/post.js '); module.exports = function (APP) {app.get ('/', function (req, res) {post.get (null, function (err, post   s) {if (err) {posts = []; } res.render (' Index ', {title: ' Home ', User:req.session.user, posts:posts, Success:req.flash (' suc  Cess '). ToString (), Error:req.flash (' Error '). ToString ()});    });    }); App.get ('/reg ', checknotlogin); App.get ('/reg ', function (req, res) {Res.render (' reg ', {title: ' Register ', User:req.session.user,success:req.flash ('    Success '). ToString (), Error:req.flash (' Error '). ToString ()});    }); App.post ('/reg ', checknotlogin); App.post ('/reg ', function (req, res) {var name = req.body.name, password = req.body.password, password_re = req.body[' password-repeat '];//Verify that the password entered by the user two times is consistent if (password_re! = password) {req.flash (' error ', ' two times entered password inconsistent! '); return Res.redirect ('/reg ');//Return to registration page}//generate password MD5 value var md5 = Crypto.createhash (' MD5 '), password = md5.update (Req.body.password). Digest (' hex '); var newuser = new User ({ Name:name,password:password,email:req.body.email});//Check whether the user name already exists user.get (newuser.name, function (err, user) {if ( User) {Req.flash (' error ', ' User already exists! '); Return Res.redirect ('/reg ');//Returns the registration page}//if there is no new user newuser.save (function (err, user) {if (err) {Req.flash (' error ', err); Return Res.redirect ('/reg ');//registration failed to return to the main album}req.session.user = user;//user information deposited Sessionreq.flash (' success ', ' registered successfully! ');    Res.redirect ('/');//return home after successful registration);});    });    App.get ('/login ', checknotlogin); App.get ('/login ', function (req, res) {res.render (' login ', {title: ' Login ', User:req.session.user, suc Cess:req.flash (' success '). ToString (), Error:req.flash (' Error '). ToString ()}); App.post ('/login ', checknotlogin); App.post ('/login ', function (req, res) {//Generate password MD5 value var MD5 = Crypto.createhash (' MD5 ') ), Password = md5.update (Req.body.password). Digest (' hex ');//Check if the user exists User.get (req.body.name, function (err, user) {if (!user) {req.flash (' error ', ' user does not exist! '); return Res.redirect ('/login ');//The user does not exist to jump to the login page}// Check if the password is consistent if (User.password! = password) {req.flash (' error ', ' Password wrong! '); return Res.redirect ('/login ');//Password error jump to login page}// After the username and password are matched, the user information is credited to Sessionreq.session.user = User;req.flash (' success ', ' Login successful! '); Res.redirect ('/');//Jump to homepage after successful login}); App.get ('/post ', checklogin); App.get ('/post ', function (req, res) {Res.render (' post ', {title: ' Publish ', User: Req.session.user,success:req.flash (' success '). ToString (), Error:req.flash (' Error '). ToString ()}); Console.log (" 222 ");}); App.post ('/post ', checklogin); App.post ('/post ', function (req, res) {var currentUser = Req.session.user,post = new post (c Urrentuser.name, Req.body.title, Req.body.post);p ost.save (function (err) {if (err) {Req.flash (' error ', err); return Res.redirect ('/');} Req.flash (' Success ', ' release success! '); Res.redirect ('/');//Publish Successful jump to homepage}); App.get ('/logout ', checklogin); App.get ('/logout ', function (req, res) {Req.session.user = Null;req.flash (' succEss ', ' logout success! '); Res.redirect ('/');//Goto page after successful logout); function Checklogin (req, res, next) {if (!req.session.user) {req.flash (' error ', ' not logged in !'); Res.redirect ('/login ');} Next ();} function Checknotlogin (req, res, next) {if (Req.session.user) {req.flash (' error ', ' logged in! '); Res.redirect (' Back ');} Next ();}};

Blog/views/blog/views/header.ejs

<! DOCTYPE html>

Blog/views/footer.ejs
</article></body>
Blog/views/index.ejs

<%-include header%><% Posts.foreach (function (post, index) {%>  <p>

Blog/views/reg.ejs

<%-include header%><form method= "post" url= '/reg ' >  user name:  <input type= "text" name= "name"/> <br/>  Password:    <input type= "password" name= "password"/><br/>  Confirm password: <input type= " Password "name=" password-repeat "/><br/>  mailbox:    <input type=" email "name=" email "/><br/>           <input type= "Submit" value= "register"/></form><%-include footer%>

Blog/views/login.ejs

<%-include header%><form method= "POST" >  user name: <input type= "text" name= "name"/><br/>  Password:  <input type= "password" name= "password"/><br/> <input         type= "Submit" value= "Login"/> </form><%-include footer%>

Blog/views/post.ejs

<%-include header%><form method= "post" url= '/post ' >  title:<br/>  <input type= "text" Name= "title"/><br/>  detail:<br/> <textarea  name= "POST" rows= "" "cols=" "></" textarea><br/>  <input type= "Submit" value= "POST"/></form><%-include footer%>

node. js a simple Blog instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.