nodejs--to build a film display platform (EXPRESS+MONGODB) __js

Source: Internet
Author: User
Tags mongodb
Chapter One: Understanding Nodejs Framework express--Routing, middleware - Routing

Routing is how to define an application's endpoint (URIs) and how to respond to a client's request.

A route consists of a URI, an HTTP request (get, post, and so on) and a number of handles, which are structured as follows: App. Method (path, [callback ...], callback), the app is an instance of the Express object, methods is an HTTP request approach, path is the server, and callback is the function to execute when the route matches.

Basic Routing Examples:

var express = require (' Express ');
var app = Express ();//app is an instance object of Express

//respond with "Hello World" when a GET request be made to the homepage
App.get ('/', function (req, res) {
  res.send (' Hello World ');
};

Routing Methods
Express defines the following routing methods for HTTP requests: Get, post, put, head, delete, options, trace, copy, lock, MKCOL, move, purge, PROPFIND, pro Ppatch, Unlock, mkactivity, checkout, merge, M-search, notify, subscribe, unsubscribe, patch, search, and connect.

Some routing method names are not compliant JavaScript variable names, and parentheses are used at this time, such as: app[' M-search '] ('/', function ...). )
App.all () is a special routing method that does not correspond to any HTTP method, and its role is to load the middleware for all requests on a path.

App.all ('/secret ', function (req, res, next) {
  console.log (' Accessing the secret section ... ');
  Next (); Pass control to the next handler
});

In the following example, a request from "/secret" will be executed regardless of the HTTP request supported by GET, POST, put, DELETE, or any other HTTP module.

Routing Path
The routing path and the request method together define the requested endpoint, which can be a string, a string pattern, or a regular expression.
The "/secret" in the example above is the routing path.

Route Handle
You can provide multiple callback functions for request processing, which behave like middleware. The only difference is that it is possible for these callback functions to invoke the next (' Route ') method and skip over the other routing callback functions. You can use this mechanism to define a prerequisite for a route, and you can give control to the remaining path if it does not make sense to continue execution on the existing path.

Mixed use of functions and function arrays to process routes:

var cb0 = function (req, res, next) {
  console.log (' CB0 ');
  Next ();
}

var CB1 = function (req, res, next) {
  console.log (' CB1 ');
  Next ();
}

App.get ('/example/d ', [Cb0, CB1], function (req, res, next) {
  Console.log (' response'll be sent by the next function ...');
  Next ();
}, Function (req, res) {
  res.send (' Hello from d! ');
});

The Response object (res) method in the following table returns a response to the client, terminating the loop of the request response. If a method is not invoked in the route handle, the request from the client is suspended.
using middleware

Express is a minimalist, entirely by routing and middleware constitute a web development framework: In essence, a express application is to invoke a variety of middleware.

Middleware (middleware) is a function that can access the Request object (req), the Response object (Response object (res)), and the middleware in the request-response loop process in the Web application, typically named The next variable.

The functions of the middleware include:

Execute any code.
Modify the request and response objects.
The end request-response loop.
The next middleware in the call stack.
If the current middleware does not have an end request-response loop, you must call the next () method to give control to the next middleware or the request will hang.

application-level middleware
As a routing handle for a middleware system, it makes it possible to define multiple routes for a path. In the following example, two routes are defined for GET requests that point to/user/:id.
The second route, while not causing any problems, will never be invoked because the first route has terminated the request-response loop.
A middleware stack that handles get requests that point to/user/:id

App.get ('/user/:id ', function (req, res, next) {
  console.log (' ID: ', req.params.id);
  Next ();
}, Function (req, res, next) {
  res.send (' User Info ');
};

Process/user/:id, print out User ID
app.get ('/user/:id ', function (req, res, next) {
  res.end (req.params.id);
});

If you need to skip the remaining middleware in the middleware stack, call the next (' route ') method to give control to the next route. Note: Next (' Route ') only uses the app. VERB () or router. VERB () loaded middleware is valid.
A middleware stack that handles get requests that point to/user/:id

App.get ('/user/:id ', function (req, res, next) {
  //If the user ID is 0, jumps to the next route
  if (req.params.id = = 0) Next (' Route ');
  //Otherwise give control to the next middleware in the stack
  else next ();//
}, Function (req, res, next) {
  //Render regular page
  Res.render (' regular ') ;
});

Process/user/:id, rendering a special page
app.get ('/user/:id ', function (req, res, next) {
  res.render (' Special ');
});

Built-in middleware
Express.static (root, [options])
Express.static is the only built-in middleware for Express. It is based on serve-static and is responsible for the hosting of static resources in Express applications.

The optional options parameter has the following properties.

App.use (Express.static (Path.join (__dirname, "bower_components"));//Static resource folder

third-party middleware
The following example installs and loads a middleware for parsing cookies: Cookie-parser

$ NPM Install Cookie-parser

var express = require (' Express ');
var app = Express ();
var cookieparser = require (' Cookie-parser ');

//Load middleware for parsing cookies
App.use (Cookieparser ());

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.