Express: Redirect within Route

Created on 18 Sep 2014  路  6Comments  路  Source: expressjs/express

How do I redirect within a route?

var express = require('express');
var router = express.Router();

router.get('/', function(req,res){
    //do something
});

router.get('/delete/:id', function(req, res){
   // redirect to / in current route??
});

Most helpful comment

@tarlabs yes, you just want to examine/concat to req.baseUrl. For your example above:

var express = require('express');
var router = express.Router();

router.get('/', function(req,res){
   //do something
});

router.get('/delete/:id', function(req, res){
  // redirect to / in current router
  res.redirect(req.baseUrl + '/');
});

All 6 comments

You can use relative paths:

res.redirect('..'); // just one '..' as {id} doesn't have a trailing slash

Okie. That should work. But it would be easier to use same paths if possible directly through some router method in future version.

Because if we use multi level path then we will have to figure out what relative path to use. Not a big deal as such, just a convenience thing

Then given your current structure req.baseUrl, may have what you are looking for.

Yeah, seconding req.baseUrl. Combining that with url or path manipulation tools like the ones in require('path') and require('url'), you should be able to easily create an argument to res.redirect that suits your needs.

@tarlabs yes, you just want to examine/concat to req.baseUrl. For your example above:

var express = require('express');
var router = express.Router();

router.get('/', function(req,res){
   //do something
});

router.get('/delete/:id', function(req, res){
  // redirect to / in current router
  res.redirect(req.baseUrl + '/');
});

Thanks a lot for the help :-). Really appreciate the fast responses from all

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wxs77577 picture wxs77577  路  3Comments

jefflage picture jefflage  路  4Comments

cuni0716 picture cuni0716  路  3Comments

dmaks9 picture dmaks9  路  3Comments

despairblue picture despairblue  路  3Comments