如何重定向到node.js中的另一个页面

aid*_*n87 16 javascript redirect ejs node.js express

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

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

我还想知道如何在点击按钮时重定向用户.

假设我在显示用户页面,我显示所有用户,然后"添加另一个使用的按钮".我怎么做?如何在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>
Run Code Online (Sandbox Code Playgroud)

Rob*_*der 39

您应该返回重定向的行

return res.redirect('/UserHomePage');
Run Code Online (Sandbox Code Playgroud)


Naz*_*ros 5

好的,我将尝试使用我的示例来帮助您。首先,您需要知道我正在为我的应用程序目录结构和自动创建像app.js这样的文件使用express。我的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>
Run Code Online (Sandbox Code Playgroud)

这里重要的是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');
});
Run Code Online (Sandbox Code Playgroud)

成功登录后,这使我可以重定向到另一个页面。有一个有用的教程,您可以检查一下页面之间的重定向:

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

要读取诸如<%= user.attributes.name%>之类的语句,让我们看一下具有以下结构的简单profile.html

<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>
Run Code Online (Sandbox Code Playgroud)

要获取用户变量的属性,必须在routing.js中初始化用户变量(在我的情况下称为index.js)。看起来像

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

我在我的对象模型中使用猫鼬:

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

var userSchema = mongoose.Schema({
    user             : {
        username     : String,
        email        : String,
        password     : String
    }
});
Run Code Online (Sandbox Code Playgroud)

随时问我进一步的问题...最好的问候,纳扎尔


Bis*_*dev 5

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

例如:

res.send('<script>window.location.href="your URL";</script>');
Run Code Online (Sandbox Code Playgroud)

或者:

return res.redirect("your url");
Run Code Online (Sandbox Code Playgroud)