node. JS Blog Instance (i) Simple blog

Source: Internet
Author: User

The first chapter of the original tutorial https://github.com/nswbmw/N-blog/wiki/_pages. Because of the version number and other reasons, in the original tutorial based on a slight modification can be achieved.

Environment:

Win7 Flagship edition 64-bit

node.js:0.10.31

mongodb:2.6.4

express:3.x

Effect: User interface:
Login interface:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzg9uz3noyw9zahvhaq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">
Login success:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzg9uz3noyw9zahvhaq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">
Post blog:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzg9uz3noyw9zahvhaq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">
Publishing success:
Source: 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. Convenient later extended var time = {date:date, year:date.getFullYear (), month:date.getFullYear () + "-" + (Date.getmon Th () + 1), day:date.getFullYear () + "-" + (Date.getmonth () + 1) + "-" + date.getdate (), Minute:date.getFullY Ear () + "-" + (Date.getmonth () + 1) + "-" + date.getdate () + "" + date.gethours () + ":" + (Date.getminutes () < 1 2} ' 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;        }//Queries the article Collection.find (query) 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. Returns the ERR message}//reads the Users collection db.collection (' Users ', function (err, collection) {if (err) {mongodb.close (); re Turn callback (ERR);//error. return ERR Message}//insert user data into the Users collection Collection.insert (user, {safe:true}, function (err, user) {Mong Odb.close (); 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 message}//Read the Users Collection db.collection (' Users ', function (err, collection) {if (err) {mongodb.cl OSE (); return callback (ERR);//error. return ERR Info}//Find username (name key) value for name a document Collection.findone ({Name:name}, function (err, user) {Mong Odb.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 the booklet 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 if username already exists user.get (newuser.name, function (err, User) { if (user) {Req.flash (' error ', ' Users already exist! '); Return Res.redirect ('/reg ');//Return to the registration page}//assume that there is no new user newuser.save (function (err, user) {if (err) {Req.flash (' error ', err); Return Res.redirect ('/reg ');//register failed to return to the main booklet page}req.session.user = user;//user information deposited Sessionreq.flash (' success ', ' register success! ');    Res.redirect ('/');//After the registration has been successfully returned to the homepage});    });    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 not present! '); return Res.redirect ('/login ');//Jump to login page if user does not exist}// 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}// Username passwords are matched, the user information is stored in 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 ', ' announced 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 ' >  username:  <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= "notes"/></form><%-include footer%>

Blog/views/login.ejs

<%-include header%><form method= "POST" >  username:<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%>


About this question


I found the answer.


Router was executed without session executed while session was used in router, I think

node. JS Blog Instance (i) Simple blog

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.