express中间件和路由

1.通常http的url是这样的:http://host[:port][path],http表示协议、host表示主机、port为端口、path指定请求资源的URI,如果URL没有给出path,一般默认为“/”(通常有客户端来补上)

2.所谓路由就是如何处理http请求中的路径部分(path)

例如,我们在express中:

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');
});

上面的代码中app.get()其实就为我们网站添加了一个路由,指定“/”这个路径由get()的第二个参数代表的函数来处理。

express可以为我们常用的http方法指定路由,使用下面方法:

app.METHOD(path, callback [, callback ...])

3.路由句柄

可以为请求处理提供多个回调函数,其行为类似中间件。唯一的区别是这些回调函数可能调用next('router')方法而略过其他路由回调函数。可以利用该机制为路由定义前提条件,如果在现在路由上继续执行没有意义,则可将控制权限交给剩下的路径

METHOD可以是get或post,如app.get(),app.post()。

其实用express构建服务器时,很重要的一部分是决定怎么响应摸个路径的请求,也即路由请求。最直接的路由配制方法,就是调用app.get()、app.post()一条一条的配置。

4.中间件

express里有个中间件(middleware)的概念。所谓中间件,就是在受到请求后和发送请求之前这个阶段执行的一些函数。

要在一条路由的处理链上插入中间件,可以使用express对象的use方法:

app.use([path,] function [, function...])

当你为某个路径安装了中间件,则当以该路径为基础的路径被访问时,都会应用该中间件。中间件的函数原型 :

function (req, res, next)

next方法,是为了让后面的中间件继续处理请求 。

5.router

express还提供一个Router对象,行为很像中间件:

var router = express.Router([options]);
// invoked for any requests passed to this router
router.use(function(req, res, next) { 
// .. some logic here .. like any other middleware next();
}); // will handle any request that ends in /events// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
 // ..});

定义了router之后也可以将其当作中间件传给app.use():

app.use('/events', router);

6.那到底什么是路由什么是middleware?

当我们访问一个地址时,服务器要对这个路径做出响应,采取一定的作用,我们可以把这个过程看作一个路由。访问的“/”即为router路径,服务器采取的动作即为middleware,即一个个特殊的函数。

猜你喜欢

转载自blog.csdn.net/qq_25461519/article/details/81240159