Create a microblog with node. js

Source: Internet
Author: User
Tags install mongodb mongodb update

Routing planning

/: Home

/u/[user]: User's homepage

/post: Post a message

/reg: User Registration

/login: User Login

/logout: User log out

Add in App.js

Where/post,/login, and/reg are registered for routing using app.post because they want to accept form information. /login and/reg also want to display the form to be filled in when the user registers, so register with App.get.

Using bootstrap

Accessing the database

MongoDB data starve is Bson, so affinity with JavaScript is strong. The operation of the data in MongoDB is in the document unit. For a query operation, we only need to specify any one of the properties of the document to filter all the documents in the database that will satisfy the criteria.

Add "MongoDB" to the dependencies attribute of Package.json: ">= 0.9.9". Then run NPM install mongodb update.

Create Setting.js in the catalog of the project to hold the connection information for the database as follows

Module.exports = {   ' myblog ',   ' blog ',   ' localhost ',  27017

Where DB is the name of the database, host is the address of the database, port is the port number of the database, Cookiesecret for Cookie encryption is not related to the database, we leave it for later use.

Then create the Models folder and create the Db.js in lime, as follows

var settings = require ('.. /settings '),    = require (' MongoDB '). Db,    = require (' MongoDB '). Connection,    = require (' MongoDB 'newnewtrue});

Session Support

Get Connect-mongo and express-session modules, add in Package.json

"Connect-mongo": "0.4.1",

Add in App.js

varSession = require (' express-session ');//If you want to use the session, you need to include this module separately var mongostore = require (' Connect-mongo ') (session); varSettings = require ('./settings ')); App.use (Session ({//the App (Flash ()) should be placed in app.use ('/', routes) before the app (Flash ()) (added later).secret:settings.cookiesecret,key:settings.db,//Cookie NameCookie: {maxage:1000 * 60 * 60 * 24 * 30},// DaysStoreNewMongostore ({db:settings.db})});

The express-session and Connect-mongo modules are used to store the information of the data into the MONGOLDB.

Secret is used to prevent tampering with the value of Cookie,key as the name of a cookie, by setting the cookie's MaxAge value to set the lifetime of the cookie, where we set the lifetime of the cookie to 30 days and set its store parameter to Mongo Store instance, storing session information in the database to avoid loss.

Flash

Flash is the Connect-flash module (Https://github.com/jaredhanson/connect-flash), which is a specific area for storing information in the session. The information is written to Flash and is cleared the next time it is displayed. A typical application is the ability to combine redirects to ensure that information is provided to the next rendered page.

Add a line of code to Package.json: "Connect-flash": "0.1.1", and then NPM install installs the Connect-flash module.

Modify App.js,

at var settings = require ('./settings '); Added after: var flash = require (' Connect-flash ');

App (Flash ()), to be placed in app.use ('/', routes);

Registration response

Under the Models folder, create a new user.js and add the following code:

var MongoDB = require ('./db '));functionUser (user) {THIS.name =User.Name;This.password =User.password;}; Module.exports =User;//Storing user Information User.prototype.save =function(callback) {//User documentation to be stored in the databasevar user ={Name:This. Name, Password:This. Password,};//Open Database Mongodb.open (function(Err, DB) {If(ERR) {Return callback (ERR);//Error, returning ERR information}//Read the Users Collection db.collection (' users ',function(Err, collection) {If(ERR) {Mongodb.close ();Return callback (ERR);//Error, returning ERR information}//Inserting user data into the Users collectionCollection.insert (user, {safe:True},function(Err, user) {Mongodb.close ();If(ERR) {Return callback (ERR);//Error, returning ERR information} Callback (NULL, user[0]);//Success! ERR is null and returns the Stored User document}); }); });};//Read user Information User.get =function(Name, callback) {//Open Database Mongodb.open (function(Err, DB) {If(ERR) {Return callback (ERR);//Error, returning ERR information}//Read the Users Collection db.collection (' users ',function(Err, collection) {If(ERR) {Mongodb.close ();return callback (ERR); // error, return err info  // 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 for the query }); }); });}; 

Through the User.prototype.save realizes the user information storage, through the User.get realizes the user information reading.

At the front of Index.js, add the following code: var crypto = require (' crypto '), User = require (' ... /models/user.js ');

Introducing the Crypto module and the User.js user model file, crypto is a core module of node. js that generates hash values to encrypt passwords.

Modify Index.js in App.post ('/reg ')

Router.post ("/reg",function(req, res) {Console.log (req.body[' Username ']); Console.log (req.body[' Password ']); Console.log (req.body[' Password-repeat ']); if(req.body[' password-repeat ']! = req.body[' password ']) {Req.flash (' Error ', ' two times the password entered is inconsistent '); returnRes.redirect ('/reg '); }    varMD5 = Crypto.createhash (' MD5 ')); varPassword = md5.update (Req.body.password). Digest (' base64 '); varNewUser =NewUser ({name:req.body.username, Password:password,}); //Check if the user name already existsUser.get (Newuser.name,function(err, user) {if(user) {err= ' Username already exists. '; }    if(Err) {Req.flash (' Error ', err); returnRes.redirect ('/reg '); } newuser.save (function(err) {if(Err) {Req.flash (' Error ', err); returnRes.redirect ('/reg '); } Req.session.user=NewUser; Req.flash (' Success ', req.session.user.name+ ' registered success '); Res.redirect (‘/‘);  });  }); });

Req.body: is the POST request information after parsing the object, such as we want to access the post to the form of the Name= "password" field value, only need to access req.body[' password ' or Req.body.password.
Res.redirect: redirect function, to achieve the page jump, more information about Res.redirect please refer to: Http://expressjs.com/api.html#res.redirect.
User: In the previous code, we used the user object directly. User is an object that describes the data, which is the model in the MVC schema. Before we used many views and controllers, this was the first time we touched the model. Unlike views and controllers, a model is a real tool for dealing with data, and without a model, a Web site is just a shell that does not play a real role, so it is the most fundamental part of the framework.

User.get: Gets a known user by user name, which is used to determine if the user name already exists. User.save can write modifications to the user object to the database.

The current user's information is written to the session object through Req.session.user:newUse to determine if the user is logged in.

Modify the navigation section to display different information for logged-in users and users who are not logged in

              if (!user) {%>                <li><a href= "/login" > Login </a></li>                <li><a href= "/reg" > Register </a ></li>              Else {  %>                <li><a href= "/logout" > Logout </a></li>              <%}%>

Page Notifications

    if (success) {%>      <div class= "alert alert-success" >        <%= success%>      </div>    <%}%>    if (Error) {%>      <div class= "alert Alert-error" >        <%= error%>      </div>    <%}%>

Landing and logging out

Router.get ('/login ',function(req, res) {Res.render (' Login ', {title: ' User Login ', User:req.session.user, Success:req.flash (' Success '). ToString (), Error:req.flash (' Error '). toString ()}); Router.post ("/login",function(req,res) {varMD5 = Crypto.createhash (' MD5 ')); varPassword = md5.update (Req.body.password). Digest (' base64 '); User.get (Req.body.username,function(err, user) {if(!user) {Req.flash (' Error ', ' User not present '); returnRes.redirect ('/login '); }               if(User.password! =password) {Req.flash (' Error ', ' User name or password is wrong '); returnRes.redirect ('/login '); } Req.session.user=user; Req.flash (' Success ', Req.session.user.name + ' login successful '); Res.redirect (‘/‘); });}); Router.get ('/logout ',function(req, res) {Req.session.user=NULL; Req.flash (' Success ', ' logout success '); Res.redirect (‘/‘);});

Page Permission Control

The logout function should only be developed for users who have logged in, and the registration and login page should block access to the logged-in user.

The use of routing middleware to achieve.

The user login status is placed in the routing middleware, and the routing middleware is added before each path.

 function   Checknotlogin (req, res, next) {  if   (Req.session.user) {Req.flash (     ' error ', ' user already logged in '  ';   return  res.redirect ('/'  function   Checklogin (req, res, next) { if  (!req.session.user) {Req.flash ( ' error ', ' user not yet logged in '  return  res.redirect ('/login ' ); } next ();}  
Router.get ("/reg",  Checknotlogin); Router.post ("/reg",  Checknotlogin); Router.get ("/ Login ",  Checknotlogin); Router.post ("/login ",  Checknotlogin); Router.get ('/logout ', Checklogin);

Create a microblog with node. js

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.