简体   繁体   English

如何处理一条不同于所有其他快递路线

[英]How to handle one express route different than all other

I'm currently using the Express router within a NodeJS application. 我目前在NodeJS应用程序中使用Express路由器。 I have simply been using app.use(app.router); 我只是一直在使用app.use(app.router); for routing and it works well. 进行路由,效果很好。 However, I'm now testing out some new routes and want to handle them differently. 但是,我现在正在测试一些新路线,并希望以不同的方式处理它们。

Ideally I would like to be able to say: 理想情况下,我想说:

var vers2Router = require('./routes/version2');

app.use('/version2', vers2Router);
app.use(app.router);

Can I do this in order to handle all /version2 routes with vers2Router and the rest simply using app.router ? 我可以这样做以使用vers2Router处理所有/version2路由,其余的仅使用app.router吗?

As of Express version 4.x, app.router has been removed. 从Express版本4.x开始, app.router已被删除。 Routes are now executed in the order they are added. 现在按添加的顺序执行路由。

Now you may use the express.Router because it will allow you to have isolated instances of routes and in your example you could create many routers with their own versioned routes. 现在,您可以使用express.Router,因为它将允许您使用隔离的路由实例,并且在您的示例中,您可以使用自己的版本化路由创建许多路由器。

Something like this: 像这样:

// app.js
'use strict';

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

var userRouterV1 = require('./routes/v1/userRouter.js');
var userRouterV2 = require('./routes/v2/userRouter.js');

app.use('/v1/api/users', userRouterV1);
app.use('/v2/api/users', userRouterV2);

app.listen(4000, function () {
  console.log('server up an running');
});

and your isolated routes version 1 : 和您的隔离路由版本1:

// /routes/v1/userRouter.js
'use strict';

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

router.get('/', function (req, res) {
  res.send('Hello v1');
});

module.exports = router;

finally your isolated routes version 2 : 最后,您的隔离路由版本2:

// /routes/v2/userRouter.js
'use strict';

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

router.get('/', function (req, res) {
  res.send('Hey v2');
});

module.exports = router;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM