Node. js Express framework Getting Started Guide and node. js Getting Started Guide

Source: Internet
Author: User

Node. js Express framework Getting Started Guide and node. js Getting Started Guide

Express Introduction
Npm provides a large number of third-party modules, including many Web frameworks, such as Express, a lightweight Web framework to be described in this chapter.

Express is a simple and flexible node. the js Web application development framework provides a series of powerful functions, such as template parsing, static file service, middleware, and route control, you can also use plug-ins or integrate other modules to help you create various Web and mobile device applications, which are currently the most popular Node-based applications. js Web development framework, and supports multiple templates such as Ejs and jade, you can quickly build a website with complete functions.

Okay. Let's get started!

1. NPM Installation

npm install express

2. Get and reference

var express = require('express');var app = express();

With the variable "app", we can call various methods of express. Just now, let's continue to work!

Create an application
After understanding the Express framework, we started to create our first express application.

Add the following content to the main file app. js of our default project:

var express = require('express');var app = express();app.get('/', function (request, response) {  response.send('Hello World!');});app.listen(80);

Note: In subsequent courses, we will use port 80 to listen for requests.

After adding the content, view the browser content through the "test address" in the right column. When you see "Hello World !" The content indicates that a simple express application has been created successfully.

Get request
We have implemented a simple express application. Next we will introduce the specific implementation of Express. First, we will first learn the common methods of express.

Get Method -- process the GET request sent by the client based on the Request Path.

Format:

app.get(path,function(request, response));

Path is the request path, and the second parameter is the callback function for processing the request. There are two parameters: request and response, which represent the request information and response information.

Example:

var express = require('express');var app = express();app.get('/', function(request, response) {  response.send('Welcome to the homepage!');});app.get('/about', function(request, response) {  response.send('Welcome to the about page!');});app.get("*", function(request, response) {  response.send("404 error!");});app.listen(80);

In the preceding example, the about page path, root path, and all paths are specified. In the callback function, the send method of the HTTP response is used to send a string to the browser.

Refer to the above Code and try to set a get request path, and then check whether the browser can successfully access this address.

Middleware <Middleware>
1. What is middleware?

Middleware (middleware) is a function used to process HTTP requests and complete various specific tasks, for example, check whether a user logs on, analyzes data, and other tasks completed before the user is finally sent to the user. Its biggest feature is that after a middleware completes processing, it can pass the corresponding data to the next middleware.

2. A middleware that does not perform any operation and only transmits the request object is like this:

function Middleware(request, response, next) {  next();}

The next in the code above is the callback function of the middleware. If it has a parameter, an error is thrown. The parameter is the error text.

Function Middleware (request, response, next) {next ('error! ');}

After an error is thrown, the subsequent middleware will not execute until an error processing function is found. If the next method is not called, the function registered later will not be executed.

Basic usage of all functions
Different from the get function. the all () function can match all HTTP verbs, that is, it can filter requests in all paths. If the all function is used to define the middleware, It is equivalent that all requests must first use this middleware.

Format:

app.all(path,function(request, response));

As shown below, we use the all function to set the Response Header Attribute before the request.

Var express = require ("express"); var app = express (); app. all ("*", function (request, response, next) {response. writeHead (200, {"Content-Type": "text/html; charset = UTF-8"}); // set the Response Header attribute value next () ;}); app. get ("/", function (request, response) {response. end ("Welcome to the Homepage! ") ;}); App. get ("/about ", function (request, response) {response. end (" welcome to the about page! ") ;}); App. get (" * ", function (request, response) {response. end (" 404-not found! ") ;}); App. listen (80 );

"*" In the above Code parameter indicates that it is valid for all paths. This method is particularly useful when processing specific prefix paths or any paths, no matter whether we request any path, we will go through the all function in advance.

As shown in, what if we skip the all function?

Use basic usage 1
Use is the method used by express to call the middleware. It returns a function.

Format:

App. use ([path], function (request, response, next) {}); // optional parameter path is "/" by default "/".

1. Use Middleware

app.use(express.static(path.join(__dirname, '/')));

As shown above, we use the use function to call express middleware to set the access path of the static file directory (this is assumed to be the root path ).

2. How to call two middleware Products consecutively, as shown in the following example:

Var express = require ('express '); var app = express (); app. use (function (request, response, next) {console. log ("method:" + request. method + "=" + "url:" + request. url); next () ;}); app. use (function (request, response) {response. writeHead (200, {"Content-Type": "text/html; charset = UTF-8"}); response. end ('example: calling two middlewares consecutively ') ;}); app. listen (80 );

The next parameter of the callback function, indicating that it accepts calls from other middleware. The next () parameter in the function body indicates that the request data is transmitted to the next middleware.

The above code first calls the first middleware, outputs a line of information on the console, and then uses next () to call the second middleware and outputs an HTTP response. Since the second middleware does not call the next method, the req object will not be passed back.

Use basic usage 2
The use method can not only call middleware, but also return different webpage content based on the requested URL, as shown in the following example:

var express = require("express");var app = express();app.use(function(request, response, next) {  if(request.url == "/") {    response.send("Welcome to the homepage!");  }else {    next();  }});app.use(function(request, response, next) {  if(request.url == "/about") {    response.send("Welcome to the about page!");  }else {    next();  }});app.use(function(request, response) {  response.send("404 error!");});app.listen(80);

The above Code uses the request. url attribute to determine the request url and then return different content.

Callback Function
The Express callback function has two parameters: request (req) and response (res). request indicates the HTTP request sent from the client, and request indicates the HTTP response sent to the client, both parameters are objects. Example:

function(req, res) {});

In later studies, we will often deal with it and remember its format!

Obtain the Host Name and path name
Today, we will first learn how to use the req object to process HTTP requests sent from the client.

Req. host returns the host Name (excluding the port number) in the request header ).

Req. path returns the path name of the requested URL.

Example:

Var express = require ('express '); var app = express (); app. get ("*", function (req, res) {console. log (req. path); res. send ("req. host to obtain the host name, req. path: Obtain the Request path! ") ;}); App. listen (80 );

Try entering any request path in the browser and viewing the host name or request path through req.

Basic query usage
Query is an object attribute that can obtain the get Request Path parameters of the client. It contains the parsed request parameter object. The default value is {}.

Var express = require ('express '); var app = express (); app. get ("*", function (req, res) {console. log (req. query. parameter Name); res. send ("test query attributes! ") ;}); App. listen (80 );

Get the object parameter value of the get Request Path Through req. query.

Format: req. query. Parameter Name; Request Path:

Example 1:/search? N = Lenka

req.query.n // "Lenka"

Example 2:/shoes? Order = desc & shoe [color] = blue & shoe [type] = converse

req.query.order // "desc"req.query.shoe.color // "blue"req.query.shoe.type // "converse"

Try to get a request with a parameter path and use the "req. query. Parameter Name" method to obtain the request parameter value.

Basic param usage
Like the property query, we can also obtain the value of the parsed request parameter object through req. param.

Format: req. param ("parameter name"); Request Path:

Example 1: Get the parameter value of the Request root path, such /? N = Lenka, the method is as follows:

Var express = require ('express '); var app = express (); app. get ("/", function (req, res) {console. log (req. param ("n"); // Lenka res. send ("use req. get the parameter object Value of the Request root path in the param attribute! ") ;}); App. listen (80 );

Example 2: We can also obtain the request object with the corresponding routing rules. Assume that the routing rule is/user/: name/, and the Request Path is/user/mike, as shown below:

App. get ("/user/: name/", function (req, res) {console. log (req. param ("name"); // mike res. send ("use req. get the parameter object value with routing rules! ");});

PS: the so-called "routing" refers to specifying different processing methods for different access paths.

After reading the example above, try to use the req. param attribute to parse a Request Path object and obtain the request parameter value.

Basic params usage
Similar to param, but params is a property that can parse request objects containing complex naming routing rules.

Format: req. params. Parameter Name;

Example 1. We can obtain the request root path as follows:

Var express = require ('express '); var app = express (); app. get ("/user/: name/", function (req, res) {console. log (req. params. name); // mike res. send ("use req. get the parameter object value with the routing rule! ") ;}); App. listen (80 );

View the running result. The function is the same as that of the param attribute. The parameter value is also obtained.

Example 2: Of course, we can also request complex routing rules, such as/user/: name/: id. Assume that the request address is/user/mike/123, as shown below:

App. get ("/user/: name/: id", function (req, res) {console. log (req. params. id); // "123" res. send ("use req. parameter object Value of complex routing rules for params attributes! ");});

For a path with routing rules for the request address, is the attribute params more powerful than the param attribute!

Send basic usage
The send () method sends a response to the browser and intelligently processes different types of data. Format: res. send ([body | status], [body]);

1. When the parameter is a String, Content-Type is set to "text/html" by default ".

res.send('Hello World'); //Hello World

2. When the parameter is Array or Object, Express returns a JSON.

res.send({ user: 'tobi' }); //{"user":"tobi"}res.send([1,2,3]); //[1,2,3]

3. When the parameter is a Number and no one mentioned above is in the response body, Express will help you set a response body. For example, 200 will return the character "OK ".

res.send(200); // OKres.send(404); // Not Foundres.send(500); // Internal Server Error

The send method automatically makes some settings when the response is output, such as HEAD information and HTTP cache support.

Articles you may be interested in:
  • Create a web calculator using node. js + express
  • The Nodejs express framework uses both the ejs template and the jade template in a project.
  • Express Route details
  • Use the template engine in Express
  • Install and configure the node. js + express development environment in win7
  • Node Connection database (express + mysql)
  • Implement File Upload Based on nodejs + express (4.x+)
  • Nodejs Express4.x Development Framework notes
  • Nodejs express tutorial
  • Nodejs express at the initial stage

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.