Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default path (route prefix) in express?

Instead of doing path + '..' foreach route - how can I prefix every route?

My route shall be

/api/v1/user 

What I don't want to do

var path = '/api/v1'; app.use(path + '/user', user); 

What I want to do

 var app = express();  app.setPath('/api/v1');  app.use(..); 
like image 920
boop Avatar asked May 01 '15 19:05

boop


People also ask

What is Router () in Express?

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. Multiple requests can be easily differentiated with the help of the Router() function in Express. js.

How do I redirect Route Express?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.

How do I register a route in Express?

log("Server started on port:", port); } registerMiddleware() { // Ignore this for now, but register all middleware in here ... } registerRoutes() { // Register all of the routes defined in the '/routes' directory } } module. exports = Server; // app.

What are Express route parameters?

In Express, route parameters are essentially variables derived from named sections of the URL. Express captures the value in the named section and stores it in the req. params property. You can define multiple route parameters in a URL.


2 Answers

Using Express 4 you can use Router

var router = express.Router(); router.use('/user', user);  app.use('/api/v1', router); 
like image 198
Explosion Pills Avatar answered Sep 30 '22 17:09

Explosion Pills


If you are using Express 4 Router you can use route() method to set the path and create a chainable route handler

app.route('/book')   .get(function (req, res) {     res.send('Get a random book')   })   .post(function (req, res) {     res.send('Add a book')   })   .put(function (req, res) {     res.send('Update the book')   }); 
like image 37
Andrew Chudinovskyh Avatar answered Sep 30 '22 16:09

Andrew Chudinovskyh