Here, we are ready to implement a microblog system from scratch with Nodejs. Features include routing control, page templates, database access, user registration, login, user sessions, and more.
The Express framework, MVC design pattern, Ejs template engine, and MongoDB database operations will be introduced.
Preparatory work
Using the HTTP module, express framework,
Nodejs's abstraction is so bad that it exposes the wrong details to the developer. You can use it to do anything that the HTTP server can do, not just to make a website, or even implement an HTTP proxy server.
Express is the Web development framework.
Realize:
Provides a higher-level interface for HTTP modules,
Routing control,
Template parsing support,
Dynamic View,
User sessions,
CSRF Protection,
Static file service,
Error controller,
Access logs,
Cache
Plugin support.
Most features are just encapsulation of common operations in the HTTP protocol, and more features require plug-ins or integration with other modules.
Rapid development
Install Express
Under the project directory
NPM install-g Express-generator
Express--help
Establish engineering
Express-t Ejs microblog because the new version has no-t command
1. How to install the Ejs template engine in a project
Use the following command to establish the basic structure of your Web site in the Nodejs guide:
Express-t Ejs Microblog
Continue running after running this command
CD microblog && npm Install (dependency properties of the installation project),
found that the installed template engine is jade, not ejs. The reason is that the current version has no-t this command, instead
EXPRESS-E microblog
After running this command, continue running CD microblog && NPM install,ejs template engine is installed
But express3 above version of the layout by default to cancel, so now in the Views folder does not generate Layout.ejs.
2. When Ejs is installed, how to use the Ejs layout template
installing Express-partials
Switch to the project directory in CMD, run
(1) npm install express-partials
or
(2) package.json
Add in the dependencies
inside "express-partials": "*"
. Then run under the project directory npm install
.
(3)然后在app.js
Inside quoteexpress-partials,引用方法:
1. path = require(‘path‘)
after that, add a referencevar partials = require(‘express-partials‘);
2. In the app.set(‘view engine‘, ‘ejs‘)后,
addapp.use(partials());
3. Growth port,
App.listen (8100,function () {
Console.log ("Server start!");
});
http://cnodejs.org/topic/515b009a6d38277306192e4e
Start the server
Structure of the project
Routing control
Template engine
Create a Weibo website
User Registration and Login
Post Weibo