在Express中从一条路线重定向到另一条路线 [英] Redirect from one route to another in Express

查看:134
本文介绍了在Express中从一条路线重定向到另一条路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nodejs中有以下路线

I have following routes in nodejs

这里是 users.js 路线

router.post('/users/login', function(request, response) {
    // let user login here and do all of the logic.

    // Once done then redirect user to dashboard in dashboard.js file
    response.redirect('/dashboard');
});

这里是dashboard.js route

here is dashboard.js route

 router.get('/dashboard', function(request, response) {
     response.render('plans');
 });

现在当我以用户身份登录时,它会尝试重定向我,然后说下面的内容。

Now when I login as a user when it tries to redirect me it says following.

cannot get Cannot GET /users/dashboard

我希望用户'重定向到 / dashboard / dashboard

I want users' to redirect to /dashboard/dashboard instead.

怎么能我在Express中将用户从一个路由重定向到另一个路由?

How can I redirect users from one route to another in Express?

推荐答案

我有同样的疑问,我来这里寻找答案但没有找到,所以我不得不自己在文档中挖掘解决方案,我找到了一个。

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.

现在回答答案。使用 res.redirect('/ dashboard')进入相对于当前路线的路径,即用户/仪表板,如果您有一个单独的仪表板路线,那么您将不得不使用它这样:
res.redirect('../ dashboard / dashboard')

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:

路线文件夹

这里是 user_home.js 路线:

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');  
}

PS:这是我关于堆栈溢出的第一个答案,很高兴我可以帮助别人。

这篇关于在Express中从一条路线重定向到另一条路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆