“express.Router”之间的区别是什么?并使用“app.get”进行路由 [英] What is the difference between "express.Router" and routing using "app.get"?
问题描述
我有一个包含以下路由代码的应用程序:
I have an app with following code for routing:
var router = express.Router();
router.post('/routepath', function(req, res) {});
现在我必须将路由代码放在不同的文件中,所以我试图使用这个方法,但它是不可能是因为代替 express.Router()
它使用:
Now I have to put routing code in different files so I tried to use this approach, but it is not working perhaps because instead of express.Router()
it uses:
app.post("/routepath", function (req, res) {});
如何使用 express路由到不同的文件express.Router()
?
为什么 app.get
, app.post
, app.delete
等,在 app.js
中使用 express.Router()
在其中?
Why app.get
, app.post
, app.delete
, etc, are not working in app.js
after using express.Router()
in them?
推荐答案
这里有一个简单的例子: / p>
Here's a simple example:
// myroutes.js
var router = require('express').Router();
router.get('/', function(req, res) {
res.send('Hello from the custom router!');
});
module.exports = router;
// main.js
var app = require('express')();
app.use('/routepath', require('./myroutes'));
app.get('/', function(req, res) {
res.send('Hello from the root path!');
});
这里, app.use()
将 Router
实例加载到 / routepath
,以便添加到 Router
实例将相对于 / routepath
。
Here, app.use()
is mounting the Router
instance at /routepath
, so that any routes added to the Router
instance will be relative to /routepath
.
这篇关于“express.Router”之间的区别是什么?并使用“app.get”进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!