• body-parser post analysis module to install the request
  • cookies to read and write cookie
  • express server
  • markdown Markdown
  • mongoose parser generator operation Mongodb database
  • swig

template parsing engine

    directory structure

  • db database directory
  • models database model file directory
  • public public directory (CSS, JS, img
  • )

  • routers routing file directory
  • schemas database file structure
  • views template view file directory
  • app.js
  • package.json

startup file

app.js file

1. to create the application, listens on port

app = express

 const (); app.get ('/', (req, res, => next) {res.send ("Hello World!");}; (3000) app.listen, (req, res, => next) {console.log ("app is running at port 3000");}); 

2.

configuration application template

  • is defined using the template engine app.engine ('html', swig.renderFile) 1 Parameters: the name of the template engine, but also the template file suffix parameter 2: for analytical method processing the contents of the
  • template set template file directory app.set ('views','./views') by using
  • registration template engine app.set ('view engine'

,'html')

3. template engine to parse the file

 / * * * read the specified file under the views directory, parsing and return to the client: 1 * * parameter template files: 2 parameters to the template parameter transfer / res.ren Der ('index'title:' content:'Hello {swig'} home'); need to cancel the template cache limits 

 swig.setDefaults 

4. development process (false {cache:}); app.set ('view Cache'false);

5.

 / / set static file hosting when users access the /public path of the file. Then the direct return app.use ('/public', express.static (__dirname +'/public')); 

  • module
  • module

  • module
  • the backstage

  • API module
 / / app.use according to different functional modules (' / ', require ('./routers/main'); app.use ('/admin'), require ('./routers/admin') app.use ('/api'); require, ('./routers/api')); 

admin.js

 VaR for the administrator module ('express express = require '); VAR router = express.Router (/admin/user router.get); / / such as access ('/user', function (req, res, next) {res.send ('User');}); module.exports = router; 

+

main front

routing module template < br> / home
/view

api

/ module content page page
/register user registration user login
/login
/comment
/comment/post

to obtain review comments submitted

background (admin) +

routing template page

/ background

user management

/user

user list category management classification list
/category/add

/category
/category/edit
classification classification add modify delete

text classification /caterory/delete Chapter

/article Nei content management

/article/add
/article/edit list add modify the contents of
/article/delete

to delete the contents of review content management

/comment comment /comment/delete

list
comment delete function development sequence

  • module function development sequence of
  • user
  • column

encoding sequence of

comments

  • defined by Schema data storage structure design
  • page display logic function

database connection (mongoDB)

mongod --dbpath=G:datadb start MongoDB server: --port=27017

is set to start the service database storage address and port of

 var ('mongoose'mongoose = require ); / / mongoose.connect database link ("mongodb://localhost:27017/blog", (ERR) => if (ERR) {{console.log ("database connection failure");}else{console.log ("database connection"); / / start the server listening port (3000, app.listen (req, res, => next) {console.log ("app is running at port 3000");});}}); 

defines the data table structure and

model for user data table (users.js) in the schema folder:

 var mongoose = require ('mongoose'); module.exports = new mongoose.Schema ({/ / / / username username:String, password password:String}) 

;

user.js

 VaR to create a model of mongoose = require in the models directory ('mongoose'); VAR (userSchema = require. /schemas/users'); module.exports = mongoose.model ('User', userSchema); 

front end user registration submitted through Ajax username and password

url: /api/register

(POST) submitted to the front end of the

 var data analysis bodyParser = require ('body-parser'); / / bodyParser / / configuration by using this method, you can add a a body app.use attribute for the req object (bodyParser.urlencoded ({extended:true})); / / API / / 1.: in the module can define a middleware, unified format var responseData; router.use (function (req, res, next) {/ / path default', when accessing the directory when the middleware called responseData = {code:0, message:''(next);};}); router.post (' / Register', (req, res, next) {=> console.log (req.body); / / username and password to judge the legality of / / to determine whether the name has been registered by res.json / (responseData) to the client returns JSON data query database (User.findOne / / / / {return a promise object username: username.Then}) (function (userInfo) if (userInfo) {{/ / database in the record... Res.json (responseData); return;} / / to the database to add the information of VaR new User (user = {username:username, password:password}); return (user.save); / / returns the promise object.Then (function)} (newUserInfo) {console.log (newUserInfo); res.json (responseData); / / save the data;}})); the success of 

cookies module using

global (app.js) registered with the

 / / cookie / / set as long as the client sends the request will be through the middleware app.use ((req, res, => next) {req.cookies cookies = new (req, RES); / * * * * analyzing the cookies information query the database to determine whether the attention of administrators to query the database is isAdmin *: the asynchronous operation, the next should be placed inside the callback * / req.userInfo = {}; if (req.cookies.get (userInfo)) {try {req.userInfo = JSON.parse (req.cookies.get ("userInfo")); / / to query the database to determine whether the administrator of User.findById (req.userInfo._id).Then (function (result) {req.userInfo.isAdmin = Boolean (result.isAdmin); (next);}}); catch (E) {next}} {else (nex); (T);}}); / / after user login or register, you can set the cookies for the req.cookies.set ("userInfo", JSON.stringify ({_id:result._id, username:result.username})); 

swig

1.

template engine variable

{{name}}

2. blockquote>

{{student.name}}

attribute

3.if

judgment

{% if name = 'Guo'%}

hello

{% ENDIF% Jing brother

}

4.for

// arr cycle = [1, 2, 3]

{for key Val in arr%,}

%

< p> {{key}} - {{Val}}< /p>

{% endfor

5.set

%}

command is used to set a variable in the context of complex

{% set foo = [0, 1, 2, 3, 4, 5]%}

{% extends'layout.html'inherited a HTML%} / / {% include%} / /'page.html'
template contains a template to the current position of the
block {% main%} XXX {% endblock%} / / a

rewrite block

6.autoescape automatic encoding

when you want to display the backend to generate HTML code in a div template, rendering automatically when encoding,
to string form. By the following way, can avoid this situation:

 < div id= article-content > false data.article_content_html}} turning {% autoescape%} {% endautoescape%} < /div> 

CRUD user management and paging user number according to the

 const User = require ('../models/user'); / / query user data of all User.find ().Then (function (users) {}); / / according to a field data query (User.findOne {username:username} (.Then) function (result) {}); / / ID according to the user query data User.findById (ID).Then (function (user) {}); / / delete data User.remove (according to ID {_id: ID}.Then ((function)) {}); / / modify data ({_id: ID} User.update {username:}, name).Then (function () {}); 

According to the two important methods of management of

limit page (Number): limited access data the number of

skip (Number): ignore the number of data before the number

number: (ignoring the current page - 1) *

 / 

page shows the number of receiving over page let = query_page Number (req.query.page) || 1; query_page = Math.max (query_page, 1); / / limit minimum 1 query_page = Math.min (Math.ceil (count / limit), query_page); / / the maximum limit of count/limit to round var cur_page = query_page; / / the current page var limit = 10; / / the page shows the number of VaR skip = (cur_page - 1) * limit; / / User.find number (.Limit) ignored (limit).Skip (skip).Then (function (users) {... / / current page page to page / page number maxPage will be the largest transmission

;}) to the page in the table structure of

 for content.js var require / / mongoose = ('mongoose'); VAR contentSch = require ('../schemas/contentSch'); module.exports = mongoose.model ('Content', contentSch); / / contentSch.js module.exports = new mongoose.Schema ({/ / - associated field classification ID category:{/ / / / type:mongoose.Schema.Types.ObjectId type, reference ref:'Category'}, / / content title title: String, description:{type: / String, default: / content:{} ', the contents of type:String, default:''}}); / / the query Content.find (.Populate) category field Association ('category').Then (contents => / / {then through this way, I They can be found in the Content table / / content.category.category_name}); 
      
This concludes the body part