What is the difference between “express.Router” and routing using “app.get”?

前端 未结 1 878
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 06:35

I have an app with following code for routing:

var router = express.Router(); 
router.post(\'/routepath\', function(req, res) {});

Now I have

相关标签:
1条回答
  • 2020-12-14 07:05

    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!');
    });
    

    Here, app.use() is mounting the Router instance at /routepath, so that any routes added to the Router instance will be relative to /routepath.

    0 讨论(0)
提交回复
热议问题