[javascript] How to redirect to another page in node.js

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.

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?

<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>

This question is related to javascript node.js redirect express ejs

The answer is


In another way you can use window.location.href="your URL"

e.g.:

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

or:

return res.redirect("your url");

The If else statement needs to be wrapped in a .get or a .post to redirect. Such as

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

or

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

@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?

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.

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 "";
}

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:

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

Ok, I'll try to help you using one my examples. First of all, you need to know I am using express for my application directory structure and for creating files like app.js in an automatically way. My login.html looks like:

...
<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:

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/

To read a statement like <%= user.attributes.name %> let's have a look at a simple profile.html which has the following structure:

<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 user variable, you have to initialize a user variable in your routing.js (called index.js in my case). This looks like

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to redirect

React-Router External link Laravel 5.4 redirection to custom url after login How to redirect to another page in node.js How to redirect to an external URL in Angular2? How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Use .htaccess to redirect HTTP to HTTPs How to redirect back to form with input - Laravel 5 Using $window or $location to Redirect in AngularJS yii2 redirect in controller action does not work? Python Requests library redirect new url

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to ejs

How to redirect to another page in node.js How can I include css files using node, express, and ejs? Loop through JSON in EJS adding .css file to ejs How to create global variables accessible in all views using Express / Node.JS? Can I use conditional statements with EJS templates (in JMVC)? Error: Cannot find module 'ejs' Node.js - EJS - including a partial