Using node. JS for Web Development

Source: Internet
Author: User

1. Install Express

NPM install-g Express-generator

The command tool is split in the 4.0+ version, so you can not install Express, but you must install Express-generator

2. New Project

Initialize an express project and install the required modules, the default format for the template engine is Jade

Express folder name

To build the Ejs format, you need to add the-E

CD folder name && NPM Install

New server

Node Bin/www or supervisor Bin/www

App.js: Boot file, or portal file
Package.json: Storage of Engineering information and module dependencies, when adding dependent modules in dependencies, running NPM install,npm checks Package.json in the current directory and automatically installs all specified modules
Node_modules: Store the modules installed in the Package.json when you add the dependent modules to the Package.json and install them in this folder
Public: Store image, CSS, JS and other files
Routes: Storing Routing files
Views: Store view files or template files
Bin: Storing executable files

The routes/index.js routing file, equivalent to the controller, is used to organize the content of the presentation:

var express = require (' Express ');  var router = Express. Router (); /* * *function(req, res, next) {Res.render (' index ', {title: ' Express ' }); Module.exports = router;       

When accessing the home page, the Jade template engine is called to render the Index.jade stencil file (replacing all of the title variables with string Express), generating a static page and displaying it in the browser.

Index.ejs template file, Routes/index.js called template. The function is to display the referenced variable, which is the property of the object passed in by the second parameter of the Res.render function.

<! DOCTYPE html>

Layout.ejs

By default, all templates inherit from Layout.jade, that is, block content is unique, and the rest is shared, and can be viewed as a page frame,

3. Routing Control

Create a routing rule

Add after Index.js

function (req, res, next) {  res.render (' index ', {title: ' Express ' }) ;

Path matching

Router.get ('/user/:username ',function(req,res) {    res.send (' User: ' + Req.params.username );})

The path rule/user/:username is automatically compiled into a regular expression, similar to the form of \/user\/([^\/]+) \/?. The path parameter can be accessed in the corresponding function through the Req.params property.

Rest-style routing rules

REST: Representational state transfer is a kind of interface style based on HTTP protocol, and fully utilize the HTTP method to realize the service of unified style interface.

Get: Request for a specified resource

POST: Submitting data to a specified resource

PUT: The request server stores a resource

Delete: The request server deletes the specified resource

The features that these 4 methods typically implement

Get: Get

POST: New

PUT: Update

Delete: Remove

Express supports the same path to bind multiple route corresponding functions. However, the request is always captured by the previous routing rule, but subsequent rules are ignored.

function (req, res) {   res.send (' All method captured ');}); App.all (function(req, res) {   res.send (' User: ' + req.params.username);});

The route control transfer method, the third parameter of the callback function next, transfers the routing control to the following rule by invoking next ().

function (req, res, next) {   console.log (' All method captured ');   Next ();}); Router.all (function  (req, res) {   res.send (' User: ' + req.params.username);});

When accessing Http://localhost:3000/user/sura, the terminal prints the ' all method captured, and the User:sura is displayed in the browser. This indicates that the request was first captured by a routing rule, completed console.log using next () to transfer control, was captured by the second rule, and returned information to the browser.

Middleware can be implemented, and can improve the reuse of code.

Template engine

is a tool for generating HTML from a page template according to certain rules. The function of the template engine is to combine the page template with the data to be displayed, it can run on the client and can run on the server side, most of the time it is directly on the server side is parsed into HTML, parsing completed and then passed to the client.

In the MVC architecture, the template engine is included on the server side, and after the user requests the control, fetch the data from the model and invoke the template engine. The template engine generates an HTML page with data and page input, which is then returned to the controller and returned to the client by the controller.

App.js Setting the location of the template engine and page templates

App.set (' Views ', Path.join (__dirname, ' views '));
App.set (' View engine ', ' Ejs ');

Routes/index.js the Exports.index function calls the template engine

Res.render (' index ', {title: ' Express '});

The function of Res.render is to invoke the template engine and return the resulting page directly to the client. It receives two parameters, the first is the name of the template, which is the target file name under the Views directory, does not contain the extension, and the second parameter is the data passed to the template.

Index.ejs

<p>welcome to <%= title%></p>

<% Code%>:javascript Codes

<%= code%>: Displays content that has been replaced with HTML special characters

<%-code%>: Display original HTML content

Page layout

Layout.ejs is a page layout template that describes the frame structure of the entire page, by default each individual page inherits from the frame, replacing the <%-body%> part. Because in general, in order to maintain a consistent style throughout the site, the

Layout is not supported after version 3.X

Method 1:include

Cut the index.html page into 3 parts: header.html, index.html, footer.html

Header.html, which is the header area of the HTML page

<! DOCTYPE html>

index.html, display area for content

<% include header.html%>

F ooter.html, for the bottom area of the page

<script src= "/javascripts/jquery-1.9.1.min.js" ></script><script src= "/javascripts/ Bootstrap.min.js "></script></body>

Method 2: Add the layout yourself

Add "express-partials" to dependencies inside Package.json: "*"

   "Dependencies":{       "Express": "3.1.0",       "Ejs": "*",       "express-partials": "*"      }

Run cmd and switch to the project directory run NPM install to get the latest version

Reference Express-partials in App.js

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

In App.set (' View engine ', ' Ejs '), add App.use below (partials ());

Using node. JS for Web Development

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.