Redirect from one route to another in Express

前端 未结 2 1341
野趣味
野趣味 2021-02-05 22:14

I have following routes in nodejs

here is users.js route

router.post(\'/users/login\', function(request, response) {
    // let user login h         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 22:36

    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.

提交回复
热议问题