你的位置:首页 > 软件开发 > Java > nodejs开发 express路由与中间件

nodejs开发 express路由与中间件

发布时间:2016-07-18 23:00:05
路由通常HTTP URL的格式是这样的:http://host[:port][path]http表示协议。host表示主机。port为端口,可选字段,不提供时默认为80。path指定请求资源的URI(Uniform Resource Identifier,统一资源定位符),如果U ...

路由

通常HTTP URL的格式是这样的:

http://host[:port][path]

http表示协议。

host表示主机。

port为端口,可选字段,不提供时默认为80。

path指定请求资源的URI(Uniform Resource Identifier,统一资源定位符),如果URL中没有给出path,一般会默认成“/”(通常由浏览器或其它HTTP客户端完成补充上)。

所谓路由,就是如何处理HTTP请求中的路径部分。比如“http://xxx.com/users/profile”这个URL,路由将决定怎么处理/users/profile这个路径。

来回顾我们在Node.js开发入门——Express安装与使用中提供的express版本的HelloWorld代码:

var express = require('express');var app = express();app.get('/', function (req, res) { res.send('Hello World!');});app.listen(8000, function () { console.log('Hello World is listening at port 8000');});
An Express application is essentially a stack of middleware which are executed serially.(express应用其实就是由一系列顺序执行的Middleware组成。)A middleware is a function with access to the request object (req), the response object (res), and the next middleware in line in the request-response cycle of an Express application. It is commonly denoted by a variable named next. Each middleware has the capacity to execute any code, make changes to the request and the reponse object, end the request-response cycle, and call the next middleware in the stack. Since middleware are execute serially, their order of inclusion is important.(中间件其实就是一个访问express应用串入的req,res,nex参数的函数,这个函数可以访问任何通过req,res传入的资源。)If the current middleware is not ending the request-response cycle, it is important to call next() to pass on the control to the next middleware, else the request will be left hanging.(如果当前中间件没有完成对网页的res响应 ,还可以通过next把router 留给下一个middleware继续执行)With an optional mount path, middleware can be loaded at the application level or at the router level. Also, a series of middleware functions can be loaded together, creating a sub-stack of middleware system at a mount point.
nodejs开发  express路由与中间件

 

  路由的产生是通过HTTP的各种方法(GET, POST)产生的,Middleware可以跟router路径跟特定的HTTP方法绑定,也可以跟所有的方法绑定。

  3.1 通过express应用的use(all),把Middleware同router路径上的所有HTTP方法绑定:

1 app.use(function (req, res, next) {2  console.log('Time: %d', Date.now());3  next();4 })
1 app.get('/', function(req, res){2  res.send('hello world');3 });4 5 6 app.post('/', function(req, res){7  res.send('hello world');8 });
nodejs开发  express路由与中间件

 

 

  4.  Express的Router对象

  当express实例的路由越来越多的时候,最好把路由分类独立出去,express的实例(app) 能更好的处理其他逻辑流程。Express的Router对象是一个简化的 app实例,只具有路由相关的功能,包括use, http verbs等等。最后这个Router再通过app的use挂载到app的相关路径下。

 

nodejs开发  express路由与中间件

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:nodejs开发 express路由与中间件

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。