【问题标题】:How to redirect to another page in node.js [duplicate]如何重定向到node.js中的另一个页面[重复]
【发布时间】:2016-04-05 19:06:49
【问题描述】:

我有一个登录页面和一个注册页面。当随机用户想要登录并且登录成功时,我想将他重定向到另一个 .ejs 页面(例如 UserHomePage.ejs),但是到目前为止,我没有尝试过任何工作。

if (loggedIn)
    {
        console.log("Success!");
        res.redirect('/UserHomePage');
    }
    else
    {
        console.log("Error!");
    }

我也想知道,如何在点击按钮时重定向用户。

假设我在显示用户页面上,显示所有用户,然后有“添加另一个使用的按钮”。我怎么做? onclick后如何将用户重定向到Register.js页面?

<h2>List of users</h2>
<ul>
<% uporabniki.forEach(function(user) { %>
<li>  
  <%= user.attributes.name %>
  <%= user.attributes.last name %>
</li>
<% }); %>
</ul>
<h3>Add another user</h3>
<form method="post">
 <input type="submit" value="Add user" />
</form>

【问题讨论】:

  • “如何在点击按钮时重定向”——这不就是 onclick 中的 location.href = '/url/to/visit' 吗?
  • @RobBrander 你的意思是 onclick="location.href='localhost:3000/Registration'" 或 onclick="location.href='/Registration'" 或其他什么?
  • 是的,
  • 谢谢,很好用! @RobBrander

标签: javascript node.js redirect express ejs


【解决方案1】:

您应该返回重定向的行

return res.redirect('/UserHomePage');

【讨论】:

  • 我们如何重定向到 nodeJS 页面并使用它触发带有请求参数(即正文)的函数?
【解决方案2】:

好的,我会尝试使用我的一个示例来帮助您。首先,您需要知道我正在使用 express 作为我的应用程序目录结构,并以自动方式创建像 app.js 这样的文件。我的 login.html 看起来像:

...
<div class="form">
<h2>Login information</h2>
<form action="/login" method = "post">
  <input type="text" placeholder="E-Mail" name="email" required/>
  <input type="password" placeholder="Password" name="password" required/>
  <button>Login</button>
</form>

这里重要的是 action="/login"。这是我在 index.js 中使用的路径(用于在视图之间导航),如下所示:

app.post('/login', passport.authenticate('login', {
    successRedirect : '/home', 
    failureRedirect : '/login', 
    failureFlash : true
}));

app.get('/home', function(request, response) {
        response.render('pages/home');
});

这允许我在成功登录后重定向到另一个页面。有一个有用的教程可以查看页面之间的重定向:

http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/

要阅读像 这样的语句,让我们看一下具有以下结构的简单 profile.html: p>

<div id = "profile">
<h3>Profilinformationen</h3>
    <form>
        <fieldset>
            <label id = "usernameLabel">Username:</label>
            <input type = "text" id="usernameText" value = "<%= user.user.username %>" />
            <br>
        </fieldset>
    </form>

要获取 user 变量的属性,您必须在您的 routing.js(在我的例子中称为 index.js)中初始化一个 user 变量。这看起来像

app.get('/profile', auth, function(request, response) {
    response.render('pages/profile', {
        user : request.user
    });
});

我正在使用猫鼬作为我的对象模型:

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');
var role     = require('./role');

var userSchema = mongoose.Schema({
    user             : {
        username     : String,
        email        : String,
        password     : String
    }
});

如有其他问题,请随时问我... 最好的祝福, 纳扎尔

【讨论】:

  • 谢谢,这很有帮助。尽管如此,我无法将您的答案标记为“正确的”,因为我已经这样做了:(
  • 是的,也许还有一个关于组合表格的问题。我如何阅读 并将其放入我的 .js 文件中。例如。我有一个项目列表,我选择一个,然后将其添加到某个用户,这意味着我需要获取项目 ID 和名称...
  • 谢谢你的信息,你能在这个stackoverflow.com/questions/67445746/…提出一些建议
【解决方案3】:

您可以通过另一种方式使用window.location.href="your URL"

例如:

res.send('<script>window.location.href="your URL";</script>');

或:

return res.redirect("your url");

【讨论】:

    【解决方案4】:

    如果用户成功登录到您的 Node 应用程序,我认为您正在使用 Express,不是吗?好吧,您可以使用res.redirect 轻松重定向。喜欢:

    app.post('/auth', function(req, res) {
      // Your logic and then redirect
      res.redirect('/user_profile');
    });
    

    【讨论】:

    • 是不是我写的完全一样,但不起作用?
    • 你使用的是 Express,因为如果你使用的是纯 Node http,重定向是不同的。
    • 是的,我正在使用快递
    【解决方案5】:

    If else 语句需要包裹在 .get 或 .post 中以进行重定向。比如

    app.post('/login', function(req, res) {
    });
    

    app.get('/login', function(req, res) {
    });
    

    【讨论】:

      【解决方案6】:

      @Nazar Medeiros - 您的解决方案使用带 Express 的护照。我没有使用护照,只是 express-jwt。我可能做错了什么,但是当用户登录时,令牌需要返回到客户端。从我目前发现的情况来看,这意味着我们必须返回一个带有令牌的 json,因此不能调用重定向。那里有什么我想念的吗?

      为了解决这个问题,我只需返回令牌,将其存储在我的 cookie 中,然后发出 ajax GET 请求(使用有效令牌)。当该 ajax 调用返回时,我将正文的 html 替换为返回的 HTML。这可能不是正确的方法,但我找不到更好的方法。这是我的 JQuery JavaScript 代码。

      function loginUser(){
        $.post("/users/login", {
          username: $( '#login_input_username' ).val(),
         password: $( '#login_input_password' ).val()
       }).done(function(res){
          document.cookie = "token = " + res.token;
          redirectToHome();
        })
      }
      
      function redirectToHome(){
        var settings = {
          "async": true,
          "crossDomain": true,
          "url": "/home",
          "type": "GET",
          "headers": {
            "authorization": "Bearer " + getCookie('token'),
            "cache-control": "no-cache"
          }
        }
      
        $.ajax(settings).done(function (response) {
          $('body').replaceWith(response);
        });
      }
      
      function getCookie(cname) {
          var name = cname + "=";
          var decodedCookie = decodeURIComponent(document.cookie);
          var ca = decodedCookie.split(';');
          for(var i = 0; i <ca.length; i++) {
              var c = ca[i];
              while (c.charAt(0) == ' ') {
                  c = c.substring(1);
              }
              if (c.indexOf(name) == 0) {
                  return c.substring(name.length, c.length);
              }
          }
          return "";
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-01
        • 1970-01-01
        • 2020-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-05
        • 1970-01-01
        相关资源
        最近更新 更多