Node.js's express frame uses upper finger South _node.js

Source: Internet
Author: User

Express Introduction
NPM provides a large number of third-party modules, including many web frameworks, such as a lightweight web framework ——— Express, which we'll cover in this chapter.

Express is a concise, flexible node.js Web application Development Framework, which provides a range of powerful features such as template parsing, static file services, middleware, routing control, and so on, and can also use Plug-ins or integrate other modules to help you create a variety of web and mobile device applications, is currently the most popular based on Node.js Web development Framework, and support Ejs, Jade and other templates, can quickly build a fully functional web site.

OK, let's start right now!

1. NPM Installation

NPM Install Express

2. Get, reference

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

Through the variable "app" we can call the various methods of Express, the fun has just begun, continue to refuel!

Create an application
Recognizing the express framework, we began to create our first Express application.

In our default project Master file App.js add the following:

var express = require (' Express ');
var app = Express ();
App.get ('/', function (request, response) {
response.send (' Hello world! ');
};

App.listen (80);

Note: We will use 80 ports for listening requests in the course of learning later.

When you have finished adding, check the browser content with the "test address" on the right-hand column, when you see "Hello world!" The content shows that a simple express application has been created successfully.

GET request
we have achieved a simple express application, the following we began to specifically describe its specific implementation, first of all, we learn the common method of Express.

Get Method--handles a request from a client that is issued by the requesting path.

Format:

App.get (path,function (Request, response));

Path is the requested route, the second parameter is the callback function that handles the request, and two parameters are request and response, representing the requested and response information.

The following 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 example above, the approach to the page path, root path, and all paths is specified. And inside the callback function, use the Send method of the HTTP response, which means sending a string to the browser.

Referring to the above code, try to set a GET request path yourself, and then the browser can access the address to request success.

middleware< Middleware >
1. What is middleware?

A middleware (middleware) is a function that processes HTTP requests to perform a variety of tasks, such as checking whether a user is logged on, analyzing data, and other tasks that need to be completed before the data is eventually sent to the user. Its biggest feature is that a middleware processing, you can transfer the corresponding data to the next middleware.

2. A middleware that does nothing to deliver only the request object, presumably:

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

Next in the code above is the callback function for the middleware. If it has a parameter, an error is thrown, and the argument is the error text.

function middleware (request, response, next) {
next (' Wrong! ');
}

After the error is thrown, the following middleware will no longer execute until an error handler is found. If the next method is not called, the function that is registered later is not executed.

Basic usage of the all function
Unlike the Get function, the App.all () function can match all HTTP verbs, that is, it can filter requests for all paths, and if the all function is used to define the middleware, then all requests must first pass through the middleware.

Format:

App.all (path,function (Request, response));

As shown below, we use the all function to set the response header property before the request.

var express = require ("Express");
var app = Express ();

App.all ("*", function (request, response, next) {
response.writehead, {"Content-type": "text/html;charset= Utf-8 "}); Sets the response Header property value
next ();
});

App.get ("/", function (request, response) {
Response.End ("Welcome to 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);

The "*" in the above code parameter is valid for all paths, and this method is particularly useful when dealing with a particular prefix path or any path, regardless of whether we request any path to pass the all function beforehand.

If so, what happens if we skip the all function and try it ourselves?

Use basic usage 1
use is the method of express calling middleware, which returns a function.

Format:

App.use ([path], function (request, response, next) {});

Optional parameter path defaults to "/".

1. Using middleware

App.use (Express.static (Path.join (__dirname, '/'));

As above, we used the use function to invoke 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 in a row, as follows:

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 ({"Content-type": "Text/html;charset=utf-8"});
 Response.End (' Example: continuous invocation of two middleware ');
};

App.listen (80);

The next parameter of the callback function, representing the invocation of the other middleware, the next () in the function body, which means that the request data is passed to the next middleware.

The code above first invokes the first middleware, outputs a line of information at the console, and then invokes the second middleware via next (), outputting the HTTP response. Because the second middleware does not call the next method, the Req object is no longer passed backwards.

Use basic Usage 2
the use method not only invokes the middleware, but also returns different Web page 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" homepage! ");
}  else {
next ();
}
});

App.use (function (request, response, next) {
if (Request.url = = "/about") {
response.send ("Welcome to" AB Out page! ");
}  else {
next ();
}
});
App.use (function (request, response) {
response.send ("404 error!");
});
App.listen (80);

The above code returns different content by Request.url properties, judging the URL of the request.

callback function
the express callback function has two parameters, such as request (req) and Response (RES), requesting HTTP requests on behalf of the client, and the request represents an HTTP response to the client, both of which are objects. Examples are as follows:

Function (req, res) {
});

In the later study, we will often deal with it, firmly remember its format it!

Get host name, path name
today we're going to learn how to use the Req object to handle HTTP requests from clients.

Req.host returns the host name (not including the port number) taken from the request header.

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

The following example:

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

App.get ("*", Function (req, res) {
console.log (req.path);
Res.send ("Req.host get host name, Req.path GET request pathname!");

App.listen (80);

Try to enter any one of the request paths in the browser and view the host name or request path by req.

Query Basic usage
query is an object property that gets the client GET request Path parameter, containing the parsed request parameter object, which defaults to {}.

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

App.get ("*", Function (req, res) {
console.log (req.query. Parameter name);
Res.send ("Test Query Properties!");

App.listen (80);

Gets the object parameter value of the GET request path through Req.query.

Format: req.query. parameter name; Request path The following example:

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 a GET request with a parameter path and use the "req.query. Parameter name" method to get the request parameter value.

Basic usage of PARAM
As with property query, we can get the value of the resolved request parameter object by Req.param.

Format: Req.param ("parameter name"); The request path is as follows:

Example 1: Gets the parameter value of the request root path, such as/?n=lenka, as follows:

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

App.get ("/", Function (req, res) {

Console.log (Req.param ("n"));//lenka

Res.send (" Use the Req.param property to get the Parameter object value of the request root path! ");
App.listen (80);

Example 2: We can also get the request object with the corresponding routing rule, assuming the routing rule is/user/:name/and the request path/user/mike, as follows:

App.get ("/user/:name/", Function (req, res) {
Console.log (req.param ("name"));//mike
Res.send (" Use the Req.param property to get the Parameter object value with the routing rule! ");

PS: The so-called "routing" means to specify different processing methods for different access paths.

Looking at the example above, try using the Req.param property to parse a request-path object and get the request parameter value.

Basic usage of params
similar to param, but params is a property that resolves a request object that contains a complex named routing rule.

Format: req.params. Parameter name;

Example 1. As an example of asking for a root path in the class, we can get this 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 the Req.params property to get the Parameter object value with the routing rule! ");

App.listen (80);

Look at the results of the run, the same as the Param property feature, and get the name parameter value as well.

Example 2: Of course, we can also request complex routing rules, such as/user/:name/:id, assuming the request address is:/user/mike/123, as follows:

App.get ("/user/:name/:id", Function (req, res) {
console.log (req.params.id);//"123"
res.send (" Use Parameter object values for complex routing rules with req.params attributes! ");

For a path with routing rules for the requesting address, the attribute params is a little more powerful than the Param property.

Send Basic usage
the Send () method sends a response message to the browser and can intelligently handle different types of data. The format is as follows: Res.send ([body|status], [body]);

1. When the parameter is a string, the Content-type default is set to "text/html".

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 of the above mentioned in the response body, Express will help you set a response body, such as: 200 will return the character "OK".

Res.send (200); OK
res.send (404);//Not Found
res.send;//Internal Server Error

The Send method automatically makes some settings when outputting the response, such as head information, HTTP cache support, and so on.

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.