Redirect from one route to another in Express

前端 未结 2 1339
野趣味
野趣味 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条回答
  • 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.

    0 讨论(0)
  • 2021-02-05 22:50
    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.

    0 讨论(0)
提交回复
热议问题