Redirect from one route to another in Express
Solution 1:
I had same doubt as you had, I came here to look for the answer but found none so I had to do some digging in the docs myself for the solution, and I found one.
So coming to the answer now. Using res.redirect('/dashboard') is taking to the path which is relative to the current route i.e users/dashboard, if you have a separate route for dashboard then you'll have to use it this way: res.redirect('../dashboard/dashboard')
Just for reference here is a preview of my project:
routes folder
here is user_home.js
route :
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.send("Hello User, welcome to user_home page");
});
router.get('/dashboard', function(req, res, next) {
res.send("Hello User, this your personal dashboard");
});
module.exports = router;
and here is the code from the route from where i am redirecting :
else {
console.log("Input validated!");
res.redirect('../user_home/dashboard');
}
P.S: This is my first answer on stack overflow, glad that I could help someone out.
Solution 2:
res.redirect('auth/login');
I had this in one of my route named 'contributions' and when it is redirected, it is rendered as 'contributions/auth/login' which is wrong.
The main thing i needed was 'localhost://port/auth/login.
i changed my ejs anchor tag to '/auth/login' which will take url from the root, It previously was 'auth/login' which took the url as current url + provided url, i.e., 'contributions/auth/login' in my case.
Hope this helps.
Solution 3:
Don't do response.redirect('/dashboard');
with a /
in it, as this will add /dashboard
to the current url. Do this instead: response.redirect('dashboard');
.