"11" Express Installation Primer and template engine Ejs

Source: Internet
Author: User

    • Objective
    • Express Introduction and Installation
    • Run the first express framework-based web
    • Template Engine Ejs
    • Express Project Structure
    • Express Project Analysis
      • App.set (Name,value)
      • App.use ([path], function)
      • App.get (name)
      • Routing Files Index.js
Objective

I've also learned some basic things about node. js, and now you're in the Web Development section.

node. JS provides the HTTP module, which provides some of the underlying interfaces that can be used directly, but it is still too tiring to develop the site directly, so the HTTP module is not just about the official api:http://nodejs.org/api/http.html

Below we go directly from the Express framework to carry out the web development, it has achieved a higher level of interface, make web development easier and faster ...

Introduction and Installation

Express is a lightweight, concise, and easy-to-use node. JS Web MVC Development Framework, which is based on node. JS, which has many of the features required for web development to encapsulate ...

http://expressjs.com/

Https://www.npmjs.org/package/express

  

  Installation

NPM install-g Express-generator

Https://github.com/visionmedia/express#quick-start

-G: Indicates a global installation

  

  

To this express is installed successfully in the Global environment!

  PS: Installation with NPM sometimes may not move, try a few more times!

Run the first express framework-based web

1. Create a Testwebapp

Express Testwebapp

  2. Install dependencies

Note the prompt after the successful installation, require the CD to the site directory, and perform the NPM Install Command installation project Dependencies ( you can see what dependencies are required under the Dependencies node of the project's Package.json file )

  3. Modify the App.js file and run

Locate App.js in the Testwebapp root directory and increase port monitoring, ctrl+b run in Sublime

App.listen (8100,function () {    console.log ("Server start!");});

  

4. Visit through the browser to see the effect

  

  To this successful run up the Basic Express framework of the web!

 Related tips:

1. After running in sublime, if you want to close, end the Node.exe process in Task Manager

2. Not running in sublime, you can execute node app in cmd, turn off CTRL + C with shortcut key

Template Engine Ejs

Created in the Testwebapp in the Express default use of the template is Jade, personally think Jade, although concise but not intuitive, so chose a more ejs.

ejs:embedded JavaScript

Https://github.com/visionmedia/ejs

  1. Create a project for Express + Ejs

Express-e Testejswebapp

CD Testejswebapp

NPM Install

  Express parameters

  usage:express [Options] [dir]  options:    -H,--help          output usage information    -V,--version       output The version number-    E,--ejs           add Ejs engine support (defaults to Jade)    -H,--hogan         add hogan.js engine sup Port-    C,--css <engine>  Add stylesheet <engine> Support (Less|stylus|compass) (Defaults to Plain CSS)    -F,--force force on         non-empty directory

2. After successful creation, open app.js, add 8100 port listener

3. Open the Routes folder under Index.js and modify the code as follows

    

var express = require (' Express '); var router = Express. Router ();/* GET home page. */router.get ('/', function (req, res) {  res.render (' index ', {title: ' 

4. Open the Views folder under Index.ejs, and modify the code as follows

  

<! DOCTYPE html>

5. Run the page to see the results

  

Here, we don't have anything to say about Express, so let's not go into too much detail, as long as we know that in the example above, when accessed via http://localhost:8100,

Will go to Index.js, while Index.js and Index.ejs pass the title and the Users object as arguments.

  Here's a look at Index.ejs.

Ejs the end of the file is the template file, you can see in the file we used three kinds of tags (this kind of label has other web development experience should be good to understand)

  1.<%-%>

When the tag receives the title: ' escaped variable.

  2.<%=%>

And this tag, from the display effect, he did not directly output HTML code to the page, the output is not escaped after the value of the variable

  3.<%%>

And this tab, from the display, he loops out the values in the parameter, the tag is the JavaScript logic code, note the opening and closing of parentheses

Here, simply get to know Ejs, and start looking at the structure of Express!

Express Project Structure

Above a new project called Testejswebapp, the template engine used by the Ejs, first look at the structure of the project

  

1.node_modules folder

This folder is the folder that is generated after the project is created, the CD to the project directory executes NPM install, and the dependencies required for the project are downloaded.

2.package.json file

This file is the project's configuration file (you can define the application name, version, dependencies, and so on)

Where do the dependencies under the Node_modules folder know? The reason is this Package.json file under the project root directory, which will look for the dependencies in this file and install the specified dependencies when executing NPM install

  3.public folder (contains images, javascripts, stylesheets)

This folder has done Web development should be a look to know, in order to store pictures, scripts, styles and other files

  4.routes folder

For storing routing files,

  5.views folder

For storing template files

Express Project Analysis

First look at the app.js.

  1.app.set (Name,value)

Set the value of the item named name to value, which sets the parameter

App.set (' Views ', Path.join (__dirname, ' views ')); The path of the template folder is set, and the main meaning of the __dirname is clear, it is a global variable in node. js that represents the path to the current execution file.

App.set (' View engine ', ' Ejs '); Set up using the template engine that we use for the Ejs

  2.app.use ([path], function)

Using this method to use the middleware, because express relies on connect, there are a large number of middleware, can be used through the App.use, the path parameter can not be filled, the default is '/' (the project is not used to explain separately, when used to self-check the middleware part of the API)

App.use (Express.static (Path.join (__dirname, ' public ')); It may be noted in this sentence that express.static () handles static requests, sets the public file, and all files in public are returned as static data files (such as styles, scripts, picture footage, and so on)

var routes = require ('./routes/index '); var users = require ('./routes/users '); App.use ('/', routes); App.use ('/users ', Users);

The above code indicates that when the user uses/accesses, call routes, that is, the Index.js file under the routes directory, where the. js suffix is omitted, and the routes file is called when the Users.js directory is accessed with/users.

This is why, in our example with http://localhost:8100/access is, the modified Index.js file code can be executed (of course, the Index.js file also write the corresponding code in order to be the effect we finally see)

  3.app.get (name)

Gets the value of the item named name

if (App.get (' env ') = = = ' Development ') {    app.use (function (err, req, res, next) {        res.status (Err.status | | 500); C4/>res.render (' error ', {            message:err.message,            error:err        });    }

Indicates that if it is a development environment, the stack information is output when handling error

4. Routing Files Index.js

Look at the following code

Router.get ('/', function (req, res) {  res.render (' index ', {title: ' 

This paragraph indicates that router.get indicates that the response function is processed by a GET request/time, and two parameters are request, response, respectively;

Res.render means that the template engine is called to parse the name index, passing in and passing the title and the users two objects as parameters;

Why does it know the Index.ejs in the table of contents of the solution board? Instead of files in other directories, or after other suffix names?

The reason is the setting in App.js:

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

And these two parameters can be used in Index.ejs, then add the Ejs part, will return the final generated page show!

This should almost be able to do something with Express+ejs, get started here first!

  Hint: About express, it is necessary to see api,application, request, response, router, middleware also provides a lot of methods!

"11" Express Installation Primer and template engine Ejs

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.