Express label (Space delimited): node. JS Express [TOC]
Installation:
The command line tool is split in the new version
npm install -g express //安装 express
And then
npm install -g express-generator //安装 express 命令行工具
Express-v The version I'm looking at now is 4.9.0 NPM start instead of node app.js
http. Server
var http = require (' http '); var server = Http.createserver (callback); Returns an HTTP. Server instance
Property:
Server.maxheaderscount maximum number of request headers, default 1000. If set to 0, no limit is made
Method:
Server.listnen (Prot) listens on a port Server.close (callback) prevents the server from receiving a new connection Server.settimeout (Msecs_time, callback) set the timeout value for the socket
Event:
- ' Request ' is triggered every time an HTTP request is received, and the Http.createserver parameter is the handler for this event by default. 2 parameters are available: req, res is HTTP respectively. Serverrequest and HTTP. An instance of Serverresponse. Represents a request and response message
- ' Connection ' is triggered when the new TCP is established. Provides 1 socket parameter net. Socket instance
- ' Close ' server shuts down when no parameter is triggered
http. Serverrequest
HTTP requests for messages, typically by HTTP. The request event for the server is sent. HTTP Request points: the request header. Request Body
Event:
When the ' data ' request comes in. The parameter chunk indicates that the received data ' end ' request body data transfer is complete when the ' close ' user ends the current request
Property:
The complete client request has been sent to completion httpversion HTTP protocol version, usually 1.0 or 1.1 method HTTP request methods such as GET, POST, PUT, DELETE and other URLs of the original request path, such as/static /image/x.jpg or/user?name=byvoid headers HTTP request Header trailers HTTP request tail (uncommon) connection current HTTP connection socket, is net. Socket instance Socket Connection Property alias client Client property alias params multi-route control object
http. Serverresponse
The HTTP response message is the information returned to the client, which determines what the user eventually sees.
Function
Res.writehead (StatusCode, [headers]) The function is called up one time in a request. StatusCode, is the HTTP status code. such as 200,404. Headers an array-like object that represents each property of the response header res.write (data, [encoding]) sends the response content, and if it is a string, it needs to be coded, default Utf-8 res.end (data, data, [encoding]) Ends the response, informing the client that all responses are complete. This function must be called once
Api
HTTP verbs are all express methods. Post change, put increment, delete delete, get check
GET
- Get handles client-issued get requests based on request path
App.get (Path, [Callback (Request, response)])
All
- All to match all HTTP verbs, which means that it can filter requests for all paths
App.all (Path, [Callback (Request, response, next)])
Use
- Use Express calls the middleware method, which returns a function. Path defaults to "/"
App.use ([path], [Callback (Request, response, next)])
- Use can not only call the middleware, but also can return different Web content according to the requested URL.
App.Use(function(Request,Response, Next) { If(Request.wr.== "/") {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. (function (request , Response) { response< Span class= "pun". send ( "404 error!" });
Post
- Processing a POST request for a specified page
App.post (Path,function (req, res));
Want to use body need to install middleware NPM installed body-parser npm install Multer
Call var Bodyparser = require (' Body-parser '); var multer = require (' Multer '); ... app.use (Bodyparser.json ()); App.use (bodyparser.urlencoded ({extended:true})); App.use (Multer ());
- Req.body parsing the client's post request parameters
- Format: req.body. Name of the parameter;
Note: The POST request sent by the form Accept and Ajax is not the same as the server send back data, Ajax is the data, the form will reflect the Web page
Param/query/params
- Gets the host name, path name. [The Req Here is the first parameter in the callback function]
Req.host returns the hostname of the request (without the port number); Req.path returns the path name of the requested URL Req.query is an object that stores the object properties of the GET request Path parameter Www.***.com/shoes?order=desc&shoe[color]=blue&shoe [type]=converse URL get: {order: ' desc ', shoe: {color: ' Blue ', type: ' Converse '}} req.param () function as above, but function as Req.param (' or Der ') returns desc
Req.param (' name ') can also get request objects with the appropriate routing rulesapp., (req, Res { Console. (req. Param "name" Res.< Span class= "PLN" >send ( "use Req.param property to get Parameter object values with routing rules!") });
// req.params 同上,但可以匹配复杂命名路由规则的请求app.get("/user/:name/:id", function(req, res) { console.log(req.params.id); });
Send
- The Send method sends a response message to the browser, and can intelligently handle different types of data that the Send method automatically makes when the response is output, such as head information, HTTP cache support, and so on, such as String, Array, Object, number. When the parameter is a string, Content-type defaults to "text/html" when the parameter is an array or an object, express returns a JSON when the parameter is a numberexpress will help you set a response body, For example: 200
Set
App.set (' View engine ', ' Ejs '); Set the default template engine App.engine ('. html ', require (' Ejs '). __express); Modify the template engine "__express", a public property of the Ejs module that represents the file name extension to render
App.set (' views ', __dirname); Set the views variable, which means the directory where the view is stored
express.static--Specifies the lookup directory for the static file App.use (Express.static (Require (' path '). Join (__dirname, ' public '));
Template operation: App.set (' views ', Path.join (__dirname, ' views ')); App.set (' View engine ', ' html '); App.engine ('. html ', require (' Ejs '). __express); Such a template suffix can make the. html but the template code is EJS code
Render
How to access a Web page template. The render function of the Res object
Res.render (view, [locals], callback); View name, locals pass-through variable for template
redirect
Allow URL redirection, jump to the specified URL and can specify the status, the default is 302 way to redirect according to the specified URL, can be within the domain path, the jump between pages can also jump to different domain names
Res.redirect ([status], URL); Res.redirect ("login");
middleware< Middleware >
Middleware (middleware) is a function that handles HTTP requests to accomplish a variety of specific tasks, such as checking whether a user is logged in, analyzing data, and other tasks that need to be done before the data is eventually sent to the user. It is the most important feature is that a middleware processing, the corresponding data can be transferred to the next middleware.
2 middleware calls in a rowApp.Use(function(Request,Response, Next){Console.Log("Method:"+Request.Method+" ==== "+"URL:"+Request.Url); Next();app. (function (request , Response) { Response. Writehead (200, { "Content-type" : "text/html; Charset=utf-8 " }); Response. ( example: continuous invocation of two middleware '
For this reason, the order in which the middleware is called is very important
- To set the access path for a static file directory
Express.static (Path.join (__dirname, '/public '))
- Express-session
VarSession= Require(' Express-session ');App.Use(Session({Secret:' Secret ',Resave:True,Saveuninitialized:False,Cookies:{MaxAge:1000*60*10 Expiration time setting (in milliseconds) }}));New middleware and set template variable valuesApp.Use(function(Req,Res, Next){Res.Locals.User=Req.Session.User; VarErr=Req.Session.Error;Reslocals.= "; if (err. Locals. Message = ' <div style= "margin-bottom:20px;color:red;" > ' + err + ' </div> ' ; next ();
- Body-parser
NPM Install body-PARSERNPM Install MulterCallVarBodyparser= Require(' Body-parser ');VarMulter= require ( ' multer ' ... app. (bodyparser. Jsonapp. (bodyparser. Urlencoded ({ Extended: )); app. (multer ());
node. JS Manual Query -4-express method