Javascript 如何重定向到 node.js 中的另一个页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36434978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect to another page in node.js
提问by aiden87
I have a login and a signup page. When random user wants to login, and login is successful, I want to redirect him to another .ejs page (for example UserHomePage.ejs), however, nothing I've tried have worked so far.
我有一个登录和一个注册页面。当随机用户想要登录并且登录成功时,我想将他重定向到另一个 .ejs 页面(例如 UserHomePage.ejs),但是,到目前为止,我尝试过的一切都没有奏效。
if (loggedIn)
{
console.log("Success!");
res.redirect('/UserHomePage');
}
else
{
console.log("Error!");
}
I would also like to know, how to redirect a user on button click.
我还想知道,如何在单击按钮时重定向用户。
Let's say I'm on display user page, where I display all of my users, then there is "add another used button". How do i do that? How do I redirect user to Register.js page after onclick?
假设我在显示用户页面上,在那里显示我的所有用户,然后是“添加另一个使用过的按钮”。我怎么做?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>
回答by Rob Brander
You should return the line that redirects
您应该返回重定向的行
return res.redirect('/UserHomePage');
回答by Nazar Medeiros
Ok, I'll try to help you using one my examples. First of all, you need to know I am using expressfor my application directory structure and for creating files like app.jsin an automatically way. My login.htmllooks like:
好的,我会试着用我的例子来帮助你。首先,您需要知道我将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>
The important thing here is action="/login". This is the path I use in my index.js(for navigating between the views) which look like this:
这里重要的是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');
});
This allows me to redirect to another page after a succesful login. There is a helpful tutorial you could check out for redirecting between pages:
这允许我在成功登录后重定向到另一个页面。有一个有用的教程,您可以查看页面之间的重定向:
http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/
http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/
To read a statement like <%= user.attributes.name %>let's have a look at a simple profile.htmlwhich has the following structure:
要阅读像<%= 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>
To get the the attributes of the uservariable, you have to initialize a uservariable in your routing.js (called index.js in my case). This looks like
要获取用户变量的属性,您必须在routing.js(在我的情况下称为index.js)中初始化一个用户变量。这看起来像
app.get('/profile', auth, function(request, response) {
response.render('pages/profile', {
user : request.user
});
});
I am using mongoose for my object model:
我为我的对象模型使用猫鼬:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var role = require('./role');
var userSchema = mongoose.Schema({
user : {
username : String,
email : String,
password : String
}
});
Ask me anytime for further questions... Best regards, Nazar
如有其他问题,请随时问我...最好的问候,纳扎尔
回答by Eduardo Pereira
If the user successful login into your Node app, I'm thinking that you are using Express, isn't ? Well you can redirect easy by using res.redirect
. Like:
如果用户成功登录到您的 Node 应用程序,我认为您正在使用 Express,不是吗?好吧,您可以使用res.redirect
. 喜欢:
app.post('/auth', function(req, res) {
// Your logic and then redirect
res.redirect('/user_profile');
});
回答by jmona789
The If else statement needs to be wrapped in a .get or a .post to redirect. Such as
If else 语句需要包含在 .get 或 .post 中才能重定向。如
app.post('/login', function(req, res) {
});
or
或者
app.get('/login', function(req, res) {
});
回答by ajpieri
@Nazar Medeiros - Your solution uses passport with Express. I am not using passport, just express-jwt. I might be doing something wrong, but when a user logs in, the token needs to return to the client side. From what I have found so far, this means we have to return a json with the token and therefor cannot call redirect. Is there something I am missing there?
@Nazar Medeiros - 您的解决方案使用带有 Express 的护照。我没有使用护照,只是 express-jwt。我可能做错了什么,但是当用户登录时,令牌需要返回到客户端。从我目前发现的情况来看,这意味着我们必须返回一个带有令牌的 json,因此不能调用重定向。有什么我在那里想念的吗?
To get around this, I simply return the token, store it in my cookies and then make a ajax GET request (with the valid token). When that ajax call returns I replace the body's html with the returned HTML. This is probably not the right way to do it, but I can't find a better way. Here is my JQuery JavaScript code.
为了解决这个问题,我只需返回令牌,将其存储在我的 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 "";
}
回答by Biswadev
In another way you can use window.location.href="your URL"
以另一种方式,您可以使用 window.location.href="your URL"
e.g.:
例如:
res.send('<script>window.location.href="your URL";</script>');
or:
或者:
return res.redirect("your url");