“express.Router"和“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()
而不是 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.Router()
将路由放在不同的文件中?
How can I put routing in different files using 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?
推荐答案
这是一个简单的例子:
// 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()
正在 /routepath
安装 Router
实例,以便任何添加到 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"和“express.Router"有什么区别?和路由使用“app.get"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!