ExpressJS - 路由

Web框架在不同的路径上提供HTML页面,脚本,图像等资源.

以下函数用于定义Express应用程序中的路由 :

app.method(路径,处理程序)

此METHOD可以应用于任何一个HTTP动词 -  get,set,put,delete.还存在一种替代方法,它独立于请求类型执行.

路径是请求运行的路径.

Handler是一个在相关路由上找到匹配的请求类型时执行的回调函数.例如,

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

app.get('/hello', function(req, res){
   res.send("Hello World!");
});

app.listen(3000);

如果我们运行我们的应用程序并转到 localhost:3000/hello ,服务器会在路径处收到get请求"/hello",我们的Express应用程序执行附加到此路由的回调函数,并发送"Hello World!"作为响应.

Hello

我们在同一条路线上也可以有多种不同的方法.例如,

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

app.get('/hello', function(req, res){
   res.send("Hello World!");
});

app.post('/hello', function(req, res){
   res.send("You just called the post method at '/hello'!\n");
});

app.listen(3000);

要测试此请求,请打开终端并使用cURL执行以下请求 :

curl -X POST"http://localhost:3000/hello"


Curl request

一种特殊的方法, 所有 ,由Express提供,使用相同的函数处理特定路由的所有类型的http方法.要使用此方法,请尝试以下操作.

app.all('/test', function(req, res){
   res.send("HTTP method doesn't have any effect on this route!");
});

此方法通常用于定义中间件,我们将在中间件章节中讨论.

路由器

定义上述路线非常繁琐.要将路由与我们的主 index.js 文件分开,我们将使用 Express.Router .创建一个名为 things.js 的新文件,并在其中键入以下内容.

var express = require('express');
var router = express.Router();

router.get('/', function(req, res){
   res.send('GET route on things.');
});
router.post('/', function(req, res){
   res.send('POST route on things.');
});

//export this router to use in our index.js
module.exports = router;

现在在 index.js 中使用此路由器,在 app.listen之前输入以下内容函数调用.

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

var things = require('./things.js');

//both index.js and things.js should be in same directory
app.use('/things', things);

app.listen(3000);

app.use 函数调用路径'/things'使用此路由附加 things 路由器.现在无论我们的应用程序在'/things'处获得什么请求,都将由我们的things.js路由器处理. things.js中的'/'路由实际上是'/things'的子路由.访问localhost:3000/things/,您将看到以下输出.

路由器事物

路由器非常有助于分离问题并将代码的相关部分保存在一起.它们有助于构建可维护的代码.您应该在单个文件中定义与实体相关的路由,并在 index.js 文件中使用上述方法将其包含在内.