阅读:4863回复:0
express中的路由到底是什么?Routing Routing refers to how an application’s endpoints (URIs) respond to client requests.
For an introduction to routing, see Basic routing. You define routing using methods of the Express app object that correspond to HTTP methods;
for example, app.get() to handle GET requests and app.post to handle POST requests. For a full list, see app.METHOD. You can also use app.all() to handle all HTTP methods and app.use() to specify middleware as the callback function (See Using middleware for details). These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function. In fact, the routing methods can have more than one callback function as arguments.
With multiple callback functions, it is important to provide next as an argument to the callback function and then call next() within the body of the function to hand off control to the next callback. The following code is an example of a very basic route.
基本路由 路由用于确定应用程序如何响应对特定端点的客户机请求,包含一个 URI(或路径)和一个特定的 HTTP 请求方法(GET、POST 等)。 每个路由可以具有一个或多个处理程序函数,这些函数在路由匹配时执行。 路由定义采用以下结构: app.METHOD(PATH, HANDLER) 其中:
以下示例演示了如何定义简单路由。 以主页上的 Hello World! 进行响应: app.get('/', function (req, res) { res.send('Hello World!'); }); 在根路由 (/) 上(应用程序的主页)对 POST 请求进行响应: app.post('/', function (req, res) { res.send('Got a POST request'); }); 对 /user 路由的 PUT 请求进行响应: app.put('/user', function (req, res) { res.send('Got a PUT request at /user'); }); 对 /user 路由的 DELETE 请求进行响应: app.delete('/user', function (req, res) { res.send('Got a DELETE request at /user'); }); 路由路径 路由路径与请求方法相结合,用于定义可以在其中提出请求的端点。路由路径可以是字符串、字符串模式或正则表达式。 Express 使用 path-to-regexp 来匹配路由路径;请参阅 path-to-regexp 文档以了解定义路由路径时所有的可能性。Express Route Tester 是用于测试基本 Express 路由的便捷工具,但是它不支持模式匹配。 查询字符串不是路由路径的一部分。 说起来,路由就是一个相当于平台或者管道的东西,负责分配URL请求,和对应函数的分配,用于确定对应函数如何响应请求的东西 |
|