I have an app with following code for routing:
var router = express.Router(); router.post('/routepath', function(req, res) {});
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) {});
How can I put routing in different files using express.Router()
?
Why app.get
, app.post
, app.delete
, etc, are not working in app.js
after using express.Router()
in them?
use(); mounts middleware for the routes served by the specific router, app. use(); mounts middleware for all routes of the app (or those matching the routes specified if you use app.
Router() is called, a slightly different mini app is returned. The idea behind the mini app is that each route in your app can become quite complicated, and you'd benefit from moving all that code into a separate file. Each file's router becomes a mini app, which has a very similar structure to the main app.
The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.
app. get is called when the HTTP method is set to GET , whereas app. use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With