Introduction to Node. js and Express

Source: Internet
Author: User
Tags xslt
This article introduces Node. js and Express in brief. It describes in detail how to use Node. js and Express to build a web server. If you are interested, please take a look. This article mainly introduces www.php1.cn/wiki/1498.html "target =" _ blank "> Node. A Brief Introduction to js and Express, detailing how to use Node. js and Express build a web server. If you are interested, take a look.

Just getting started with how to use Node. js and Express to build a web server does not describe much conceptual stuff.

1. Introduction to Nodejs

= Node is the server running environment in the Javascript language. =

The so-called "running environment" has two meanings: first, the Javascript language runs on the server through Node, in this sense, Node is a bit like a Javascript virtual machine; second, Node provides a large number of tool libraries, in this sense, Node is the Javascript tool library.

Node uses Google's V8 engine as a Javascript interpreter. It calls operating system resources through its own libuv library.

Ii. Download and install Node. js

2.1 Download Node. js

The official website will provide you with the most suitable version based on your current operating system.

2.4 use Node. js to run Javascript code

Create a new nodeproject directory and a new js file. 01_hello.js

var num1 = 10;var num2 = 20;console.log(num1 + num2);

On the windows console, switch the directory to the directory where the js file is located. Enter

node 01_hello.js

Create a project directory named Node_Hello. Go to the directory and create a package. json file with the following content:

{ "name": "Node_Hello", "description": "nodejs hello world app", "version": "0.0.1", "private": true, "dependencies": {  "express": "4.x" }}

The code above defines the project name, description, version, and so on, and specifies the Express that requires version 4.0 or later.

= Log on to the project directory on the console first. Then, run the following command to download Express.

npm install

3.2 Create a Startup File

In the preceding project directory, create a new startup file named = index. js =. Write the following code:

Var express = require ('express '); var app = express (); app. get ('/', function (req, res) {res. send ('hello, this is our first nodejs Project');}); app. listen (0, 8080 );

3.3 run the index. js File

node index.js

3.4 access through a browser

Enter the following address in the browser to access the web site we just set up.

127.0.0.1: 8080

4. Use Webstorm to build a Node. js web Application

It is more convenient to build a Node. js application using webstorm.

4.1 download and install WebStorm.

After the download is complete, install it directly.

4.2 create a Node + Express Application

App. js: Startup file, or entry file

Package. json: Stores project information and module dependencies. When dependency modules are added to dependencies, run npm install. npm checks the package in the current directory. json, and automatically install all specified modules

Node_modules: stores the modules installed in package. json. After you add and install the dependent modules in package. json, store them in this folder.

Public: Stores image, css, js, and other files.

Routes: stores route files

Views: stores view files or template files.

Bin: stores executable files (www)

4.4 description of major files

4.4.1 app. js

// Loading module var express = require ('express '); var path = require ('path'); var favicon = require ('serve-favicon '); var logger = require ('Morgan '); var cookieParser = require ('cookie-parser'); var bodyParser = require ('body-parser '); // load the route file var index = require ('. /routes/Index'); var users = require ('. /routes/users '); // generate an express instance var app = express (); // view engine setup/* set the views folder to the directory where the view files are stored, that is, the place where the template file is stored, dirn Ame is a global variable that stores the directory where the script is currently being executed. */App. set ('view', path. join (dirname, 'view'); // you can specify ejsapp as the template engine. set ('view engine ', 'ejs'); // uncomment after placing your favicon in/public // app. use (favicon (path. join (dirname, 'public', 'favicon. ico '); // load the Log Middleware app. use (logger ('dev'); // load the json-parsed middleware app. use (bodyParser. json (); // load the middleware that parses the urlencoded Request body. Post request app. use (bodyParser. urlencoded ({extended: false}); // loads the middleware app that parses cookies. use (cookieParser (); // set the public folder to the app directory where static files are stored. use (express. static (path. join (dirname, 'public'); // route controller. App. use ('/', index );// http://localhost:3000app.use ('/Users', users );// http://localhost:3000/users// Catch 404 and forward to error handlerapp. use (function (req, res, next) {var err = new Error ('not found'); err. status = 404; next (err) ;}); // error handlerapp. use (function (err, req, res, next) {// set locals, only providing error in development res. locals. message = err. message; res. locals. error = req. app. get ('env') = 'development '? Err: {}; // render the error page res. status (err. status | 500); res. render ('error') ;}); // export the app. Elsewhere, you can obtain this object module. exports = app through require ("app;

4.4.2 bin/www

#! /Usr/bin/env node // indicates the node Executable File/*** Module dependencies. * /// introduce us to the app. var app = require ('.. /app'); // introduce the debuger module and print the debug log var debug = require ('debug') ('Hello: Server '); // introduce the http module var http = require ('http');/*** Get port from environment and store in Express. */var port = normalizePort (process. env. PORT | '000000'); app. set ('Port', port); // set the port number/*** Create HTTP server. * // create an Http server var server = Http. createServer (app);/*** Listen on provided port, on all network interfaces. * /// listen to the specified port server. listen (port); // listens for error events. OnError is the callback function server when an error occurs. on ('error', onError); // listens to the listening Event server. on ('listening', onListening);/*** Normalize a port into a number, string, or false. */function normalizePort (val) {var port = parseInt (val, 10); if (isNaN (port) {// named pipe return val ;} if (port> = 0) {// port number return port;} return false;}/*** Event listener for HTTP server "error" event. */function onError (erro R) {if (error. syscall! = 'Listen') {throw error;} var bind = typeof port = 'string '? 'Pipele' + port: 'Port' + Port; // handle specific listen errors with friendly messages switch (error. code) {case 'eaccesss': console. error (bind + 'requires elevated privileges '); process. exit (1); break; case 'eaddrinuse': console. error (bind + 'is already in use'); process. exit (1); break; default: throw error;}/*** Event listener for HTTP server "listening" event. */function onListening () {v Ar addr = server. address (); var bind = typeof addr === 'string '? 'Pipele' + addr: 'Port' + addr. port; debug ('listening on' + bind );}

4.4.3 routes/index. js

Var express = require ('express '); var router = express. router ();/* GET home page. */router. get ('/', function (req, res, next) {res. render ('index', {title: 'yu Zhi Tong Chuang '}) ;}); module. exports = router;/* generate a route instance to capture the GET request to access the home page, export the route and go to the app. js through app. use ('/', routes); load. In this way, when you access the home page, res will be called. render ('index', {title: 'yu Zhi Tong Chuang '}); rendering views/index. the ejs template is displayed in the browser. */

4.4.4 Optimization of Route writing

In the front = app. js =, It is troublesome to add a route for each template. In fact, you should submit the route adding task to index. js. That is, you can place multiple routes in one Routing File.

// Load the route file var index = require ('. /routes/Index'); // remove var users = require ('. /routes/users '); // remove // route controller. App. use ('/', index); // http: // localhost: 3000 // remove the app. use ('/users', users); // http: // localhost: 3000/users // remove

You can change it:

var routes = require('./routes/index');routes(app);

= Index. js = optimized the file:This makes it much easier to manage

Module. exports = function (app) {// a get request route http: // localhost: 3000 app. get ("/", function (req, res) {res. render ("index", {title: "abc"}); // another request route: http: // localhost: 3000/abc app. get ("/abc", function (req, res) {res. render ("index", {title: "Yu Zhi Tongchuang" + req. path })});}

4.4.5 ejs Template

Template Engine is a tool that combines page templates with the data to be displayed to generate HTML pages. If the routing Control Method in express mentioned above is equivalent to the Controller in MVC, the template engine is equivalent to the view in MVC.

The function of the template engine is to combine the page template with the data to be displayed to generate an HTML page. It can run both on the server and on the client. Most of the time, it is directly parsed as HTML on the server, and then transmitted to the client after the parsing is complete, therefore, the client cannot even determine whether the page is generated by the template engine. Sometimes the template engine can run on the client, that is, in a browser. A typical example is XSLT, which uses XML as the input to generate HTML pages on the client. However, due to browser compatibility issues, XSLT is not very popular. Currently, the template engine is run on servers.

In the MVC Architecture, the template engine is included on the server. After obtaining the user request, the Controller obtains data from the model and calls the template engine. The template engine uses data and page templates as input to generate an HTML page and return it to the controller. The controller returns the page to the client.

= Ejs is a template engine that is easy to use and well integrated with express. =

We use the following two lines of code to set the storage location of the template file and the template engine used: (the settings in the app. js file)

app.set('views', dirname + '/views');app.set('view engine', 'ejs');
   <%= title %>  
     <%= title %>  

Welcome to <%- title %>

Note:

The tag system of ejs is very simple. It has only the following three tags:

  1. <% Code %>: Javascript code.

  2. <% = Code %>: displays content with special characters replaced with HTML. (That is, if the code contains tags, it will be output as is and will not be parsed by the browser)

  3. <%-Code %>: displays the original HTML content. (If there is a tag, a hyperlink is displayed in the browser)

Routing code:

Router. get ('/', function (req, res, next) {res. render ('index', {title: "Baidu"}) ;}); // the corresponding code in ejs will be replaced with the title value.

The generated code:

   Baidu  
   Baidu

Welcome to Baidu

The above is a brief introduction to Node. js and Express's getting started (text) Details, please pay attention to other related articles in the first PHP community!

Related Article

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.