node. JS's Express One

Source: Internet
Author: User

The HTTP module is also known earlier, but it does not support session, cookie, etc. Express is the encapsulation of the HTTP module, but also support the session, it is also better to use. Express is a bit more like an IIS server. It is also part of the content of a module, so of course it is to add the Express module NPM install Express first. Then you create the object and use it.

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

First, express settings

Express provides some application settings that control the behavior of the Express server. These settings define the environment and how Express handles JSON parsing, routing, and views. The Express object provides set (Setting,value), enable (setting), disable (setting) methods to set values for the application settings. Since you can set it, you can get it. Express uses get (setting), enable (setting), disable (setting) to get the set value.

Here are some of its settings:

ENV: Defines the environment pattern strings, such as development (DEV), testing (test), and production (production). Default Process.env.NODE_ENV

Trust_proxy: Enable/Disable support for the direction agent. Default disabled (disabled).

JSONP Callback Name: Defines the default callback name for JSONP requests, default? callback=

JSONP Replacer: Defines the JSON replacer callback function. Default NULL.

Case Sensitive routing: enable/disable sensitivity. Default disabled.

Strict routing: Enable/disable strict routing. For example,/home and/home/are not the same. Default disabled.

View cache: Enables/disables the compilation cache of the views template, which preserves the cached version of the compiled template. Default disabled.

View Engine: Specifies the default template engine extension that should be used if the file name extension is omitted from the view when the template is rendered

Views: Specifies the path that the template engine uses to find the view template. Default./views.

Second, start the Express server

Use the App.listen (port) call to bind the underlying HTTP connection to port (port) and start listening on it. The top-level HTTP connection uses the Listen () method on the server object created in the HTTP library to produce the same connection. In fact, the value returned by Express () is actually a callback function that maps the callback functions passed to the Http.createserver () and Https.createserver () methods.

var express=require (' Express '); var http=require (' http '); var app=Express (); Http.createserver (APP). Listen (8080); App.get ('/',function (req,res) {    res.send (' Hello World  ');})
"C:\Program Files (x86) \jetbrains\webstorm 11.0.3\bin\runnerw.exe"F:\nodejs\node.exe Express_http.jsmodule.js:327Throwerr; ^Error:cannot Find Module' Express 'At function.module._resolvefilename (module.js:325:15) at Function.module._load (module.js:276:25) at Module.require (module.js:353:17) at require (internal/MODULE.JS:12:17) at object.<anonymous> (f:\nodejsdemo\express_http.js:12:14) at Module._compile (module.js:409:26) at Object.module._extensions. JS (module.js:416:10) at Module.load (module.js:343:32) at Function.module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) Process finished withExit code 1

If the above error indicates that the module express cannot be found, you can execute NPM install Express in the source folder to resolve

Third, routing

1. Implementing routing

Routing is to find the physical path to the server based on the virtual path of the HTTP request. There is also a routing table in. NET MVC, which is pretty much the same.

The Express module provides functions to implement. App.<method> (Path,[meddleware,..],callback)

Method:get, post and other request methods

Meddleware: The middleware function to be applied before the callback function is executed

Express also provides a way to App.all (). The callback function App.all () invokes each request for the specified path, not just the HTTP method. App.all () can accept the * character as a wildcard for the path, which is a good way to implement logging request logs or other special functions to handle requests.

2. Applying parameters in Routing

Application parameters mean change, not dead and unchanging. NET custom routing is also, you can regist routes.

There are 4 main methods of Express:

1. Query string

This is the most basic of the most common. This is done by adding the key=value&key1=value1 to the URL path.

2.post parameters

This will use the middleware body-parser. So skip first.

3. Regular expression App.get (regular, function (Req,res) {})

For example: App.get (/^\/book\/(\w+) \:(\w+), $/,callback), you can get parameters for URL paths via Req.param[index]

4. Apply route parameters using defined parameters

App.get ('/user/:userid ', callback). Parameters can be obtained by Req.param (parameter name).

To apply a callback function for a defined parameter:

There is an advantage to using a defined parameter, and if you define a parameter in the URL, you can specify the callback function that is executed. When you parse a URL, if Express discovers that a parameter has a registered callback function, it invokes the callback function of the parameter before calling the route handler, and can register multiple callback functions for a route.

Use App.param (param,function (req,res,next,value) {}) to implement a callback function for the defined parameters.

PARAM: The parameter name defined

Nest: callback function for the next App.param () callback that is registered. You must call next () in the callback function, or the callback chain will be corrupted.

Value: The values of the parameters that are resolved from the URL path.

Demo Code:

varExpress = require (' Express ');varurl = require (' URL '));varApp =Express (); App.listen (8080); App.get (‘/‘,function(req, res) {Res.send ("Get Index");}); App.get ('/find ',function(req, res) {varUrl_parts = Url.parse (Req.url,true); varquery =Url_parts.query; varResponse = ' Finding Book:author: ' + Query.author + ' Title: ' +Query.title; Console.log (' \nquery URL: ' +Req.originalurl);  Console.log (response); Res.send (response);}); App.get (/^\/book\/(\w+) \:(\w+)? $/,function(req, res) {varResponse = ' Get book:chapter: ' + req.params[0] + ' Page: ' + req.params[1]; Console.log (' \nregex URL: ' +Req.originalurl);  Console.log (response); Res.send (response);}); App.get ('/user/:userid ',function(req, res) {varResponse = ' Get User: ' + req.param (' userid ')); Console.log (' \nparam URL: ' +Req.originalurl);  Console.log (response); Res.send (response);}); App.param (' UserID ',function(req, res, next, value) {Console.log ("\nrequest received with UserID:" +value); Next ();});///find?author=brad&title=node///book/12:15///user/4983

In the browser to enter Http://127.0.0.1:8080/find,/find?author=brad&title=node,/book/12:15,/user/4983 will have a bit of output

"C:\Program Files (x86) \jetbrains\webstorm 11.0.3\bin\runnerw.exe"/find/find?author=brad& Title=node/book/12:15 page:15 with userid:4983/user/4983  4983

There is only one parameter in the custom parameter above, now take a look at the two parameters and apply the callback function to both parameters.

varExpress = require (' Express ');varurl = require (' URL '));varApp =Express (); App.listen (8080); App.get ('/user/:userid/pwd/:p wd ',function(req, res) {varResponse = ' Get User: ' + req.param (' userid ')); Console.log (' \nparam URL: ' +Req.originalurl);  Console.log (response); Res.send (response);}); App.param (' UserID ',function(req, res, next, value) {Console.log ("\nrequest received with UserID:" +value); Next ();}); App.param (' PWD ',function(req, res, next, value) {Console.log ("\nrequest received with pwd:" +value); Next ();});
"C:\Program Files (x86) \jetbrains\webstorm 11.0.3\bin\runnerw.exe" with userid:4983   with pwd:123456/user/4983/pwd/1234564983

node. JS's Express One

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.