Use nodejs to develop Weibo instances and use nodejs to develop blogs

Source: Internet
Author: User

Use nodejs to develop Weibo instances and use nodejs to develop blogs

I have been persistently engaged in front-end development before. In recent days, I started to learn nodejs. As a front-end developer, it is naturally excited to see such a background written in javascript. However, after all, the background is different from the front-end. During the learning process, there are still many problems.

To start learning node. JS, I first chose the book "go deep into node. js". After reading several chapters, I came to the conclusion that it is a good book, but I still cannot write node. js! Then I chose another teaching material "nodejs Development Guide". After reading "go deep into nodejs", I skipped the first few chapters of this book and wrote the microblog instance of chapter 5 of this book. As a newbie, during the writing process, I gradually discovered that many of the Code in the book is no longer usable due to the upgrade of the express version. This is a really painful experience for new beginners !! In the spirit of sharing and learning, we hereby provide the "nodejs Development Guide" Weibo instance express4.x version source code and issues worth attention during the compilation process.

First, let's take a look at the current express version:

This has greatly changed with the express2.x version used in books. For new features of the express4 version, you can look at this: http://scotch.io/bar-talk/expressjs-4-0-new-features-and-upgrading-from-3-0

Let's not talk much about it. Let's start our Project Creation journey.

First, create a folder, use cmd to enter the folder, and prepare to create a project. As mentioned in the book, the command for creating a project should be:

  express -t ejs microblog

The problem is that the express-t parameter is invalid. The default template engine of the latest express version is jade. To use ejs, we need to create a project as follows:

  express -e ejs microblog

As stated in the book, we run the Code directly:

  supervisor app.js

Enter http: // localhost: 3000/in the browser and you will not be able to see the expected results in the book. js app. use ('/', routes); Add the following:

   app.listen(3000);
     Console.log(something happening);

Following the steps in the book, we will find a problem because it is not layout in the views folder. ejs and index. this is because the latest version of express does not support the partials method of the ejs module, so you need to install additional modules:

  npm install express-partials

Then add the following in app. js:

  var partials = require('express-partials');  app.use(partials());

Note that this line must be added to the app. set ('view engine ', 'ejs'); if it is added to the app. use ('/', routes); later, css references will fail, and the bloggers still do not understand the cause.

In this case, you can create the layout. ejs file in views, and then copy the layout. ejs code on page 1 of the book to the new file. Then run the code to see the following results:

The above steps are not a problem. The problem lies in a series of problems connecting to the database! As described below:

In order to perform the following operations, we first need to install the MongoDB database, the blog author recommended: http://be-evil.org/install-mongodb-on-windows7.html

I have read many blogs on MongoDB installation. This is the most effective one I have ever seen.

For the new version of express, connecting to the database as in the book will report an error. When connecting to the files required by the database, settings. js. There is no problem according to the book, but the db in models. js requires some changes. If you follow the code in the book:

  var settings = require('../settings');  var Db = require('mongodb').Db;  var Connection = require('mongodb').Connection;  var Server = require('mongodb').Server;  module.exports = new Db(settings.db, new Server(settings.host, Connection.DEFAULT_  PORT, {}));

The following problems may occur:

After the blogger google, he discovered that he had to write in the following format:

   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});

When referencing the settings module:

  var settings = require('../settings');

:

This is because the latest express version needs to reference this module as follows:

  var settings = require('./settings');

However, after solving this problem, the following pain points have emerged:

At first, I couldn't figure it out, but when google was around, a buddy gave a good answer:

Http://www.cnblogs.com/yumianhu/p/3709558.html

In other words, in express4, We need to install the express-session package by ourselves, and then add reference:

  var session  = require('express-session');

The original database reference also needs to be changed:

  var MongoStore = require('connect-mongo')(session);

And the code:

  app.use(express.session({  secret: settings.cookie_secret,  store:new MongoStore({   db: settings.db  })}));

You need to rewrite it:

  app.use(session({    secret: settings.cookie_secret,    store: newMongoStore({     db : settings.db,    })   }));

For view interaction mentioned in the book, the original code is:

  app.dynamicHelpers({    user: function(req, res) {      return req.session.user;    },    error: function(req, res) {      var err = req.flash('error');      if (err.length)        return err;      else        return null;    },    success: function(req, res) {      var succ = req.flash('success');      if (succ.length)        return succ;      else        return null;    },  });

In the latest version of express, you need to change it:

  app.use(function(req, res, next){   console.log("app.usr local");   res.locals.user = req.session.user;   res.locals.post = req.session.post;   var error = req.flash('error');   res.locals.error = error.length ? error : null;   var success = req.flash('success');   res.locals.success = success.length ? success : null;   next();  });

Flash is used in the registration page, but the latest version of express does not support flash. You need to use npm install connect-flash first. Then add the following code in app. js:

  app.use(flash());

Next, follow the steps in the book. Basically, there will be no problems. In the end, we will be able to achieve the desired results ~ :

It should be noted that there were a lot of problems when I followed the book to write this small application, that is, many of the problems encountered above, but the bloggers kept google in the spirit of independent research, finally, I jumped out of the trap and got the final result. I hope my friends from this blog can study it well and take a good look at the following link. It may also be your problem, if you encounter any problems while writing code with books, please contact us ~

The above is all the content of this article. Please take a moment to share the article with your friends or leave a comment. Thank you for your support!

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.