Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {}); 

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?

like image 834
XIMRX Avatar asked May 12 '14 10:05

XIMRX


People also ask

What is the difference between adding Middlewares using router use () and app use ()?

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.

What is the difference between router and 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.

What does the Express router do?

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.

What is the difference between app use and app get?

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.


1 Answers

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.

like image 94
mscdex Avatar answered Oct 12 '22 22:10

mscdex