Javascript 如何重定向到node.js中的其他页面

Javascript 如何重定向到node.js中的其他页面,javascript,node.js,redirect,express,ejs,Javascript,Node.js,Redirect,Express,Ejs,我有一个登录和注册页面。当随机用户想要登录,并且登录成功时,我想将他重定向到另一个.ejs页面(例如UserHomePage.ejs),但是,到目前为止,我尝试的都没有成功 if (loggedIn) { console.log("Success!"); res.redirect('/UserHomePage'); } else { console.log("Error!"); } 我也想知道,如何重定向一

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

if (loggedIn)
    {
        console.log("Success!");
        res.redirect('/UserHomePage');
    }
    else
    {
        console.log("Error!");
    }
我也想知道,如何重定向一个按钮点击用户

假设我在显示用户页面上,在那里我显示了我所有的用户,然后是“添加另一个使用过的按钮”。我该怎么做?单击后如何将用户重定向到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>
用户列表
添加其他用户
如果用户成功登录到您的节点应用程序,我认为您正在使用Express,不是吗?您可以使用
res轻松重定向。比如:

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

您应该返回重定向的行

return res.redirect('/UserHomePage');

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

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


好的,我会用我的一个例子来帮助你。首先,您需要知道我正在使用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>
这允许我在成功登录后重定向到另一个页面。有一个有用的教程,您可以在页面之间进行重定向:

要阅读类似于的语句,让我们看一看简单的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>
我将mongoose用于我的对象模型:

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

var userSchema = mongoose.Schema({
    user             : {
        username     : String,
        email        : String,
        password     : String
    }
});
随时问我进一步的问题。。。 顺致敬意,
Nazar

@Nazar Medeiros-您的解决方案使用带Express的passport。我不是用护照,只是用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 "";
}
函数登录用户(){
$.post(“/users/login”{
用户名:$('#登录\输入\用户名').val(),
密码:$('#登录_输入_密码').val()
}).完成(功能(res){
document.cookie=“token=”+res.token;
重定向到home();
})
}
函数redirectToHome(){
变量设置={
“异步”:true,
“跨域”:正确,
“url”:“/主页”,
“类型”:“获取”,
“标题”:{
“授权”:“持有人”+getCookie(“令牌”),
“缓存控制”:“无缓存”
}
}
$.ajax(设置).done(函数(响应){
$('body')。替换为(响应);
});
}
函数getCookie(cname){
变量名称=cname+“=”;
var decodedCookie=decodeURIComponent(document.cookie);
var ca=decodedCookie.split(“;”);

对于(var i=0;i,您可以通过另一种方式使用
window.location.href=“您的URL”

e、 g:


“如何在点击按钮时重定向”--这不只是onclick中的location.href='/url/to/visit吗?@RobBrander您的意思是像onclick=“location.href='localhost:3000/Registration'”或onclick=“location.href='/Registration'”或者其他什么?是的,注册谢谢,很好!@RobBranderisn我写的东西不完全一样,但不起作用?你使用的是Express,因为如果你使用纯节点http,重定向是不同的。是的,我使用的是Express谢谢,这非常有帮助。尽管我不能将你的答案标记为“正确的一个”既然我已经这么做了:(yeh可能是关于组合表的另一个问题。我如何阅读并将其放入.js文件中。例如,我有一个项目列表,我选择了一个,然后将其添加到某个用户,这意味着我需要获取项目id和名称……感谢您提供的信息,您能就此提出一些建议吗?我们如何重定向到nodeJS页面并触发函数h请求参数(即主体)是否与之匹配?
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
    }
});
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 "";
}
res.send('<script>window.location.href="your URL";</script>');
return res.redirect("your url");