0

I'm learning the basics of Node.js + MongoDB and some other related tools, but I'm stuck in a simple login screen I made, the goal is, once the right credentials are given, to redirect to index.html which only has a text "welcome!". I've taken a look at different places (official API, tutorials, this page, etc.) but can't see my error yet.

This is my server:

var http = require('http');
var hostname = 'localhost';
var port = 3000;

var mongojs = require("mongojs");
var express = require("express");

const HOME_URL = "/";
const LOGIN_URL = "/login";
const LOGIN_ACTION_URL = "/doLogin";
const INDEX_URL = "/index";

var app = express();
var db = mongojs("gus:1234@127.0.0.1:27017/awesomeapp");

app.set("views", __dirname + "/public/views");
app.engine('html', require('ejs').renderFile);

app.get(HOME_URL, function(request, response) {
    response.redirect(LOGIN_URL);
});

app.get(LOGIN_URL, function(request, response) {
    response.render("login.html");
});

app.get(INDEX_URL, function(request, response) {
    response.render("index.html");
});

app.get(LOGIN_ACTION_URL, function(request, response) {
    db.users.find({
        user: request.query.user,
        pass: request.query.pass
    }, function(err, doc) {
        if(err) {
            console.log(JSON.stringify(err));
            response.end("An error ocurred");
            return;
        }

        if(doc.length == 0) {
            console.log("invalid_credentials");
            response.end("invalid_credentials");
            return;
        }

        console.log("user found: " + JSON.stringify(doc));

        // This is my problem:
        response.redirect(INDEX_URL);
    });
});

app.listen(port);

and this is done in the login view:

$.ajax({
    url: "/doLogin",
    type: "GET",
    data: {
        user: $("#user").val().trim(),
        pass: $("#pass").val()
    }
}).done(function(data, textStatus, jqXHR) {
    if(data == "invalid_credentials") {
        $("#alert-wrong-credentials").show(100);
    } else if(data == "ok") {
        $("#alert-wrong-credentials").hide();
    }
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(errorThrown);
});

I can successfully return the error string "invalid_credentials" when trying non-existing credentials, and I can see the user data when I enter the right ones:

user found: [{"_id":"58af514cb63980d2e8a51fed","user":"gus","pass":"123"}]

but I'm unable to redirect to the index.html page.

  • The redirect you're trying to use will only work if you're visiting the page. But you are requesting it via Ajax. Which means you have to redirect in the client, in your `date == "ok"` block, using `document.location.href = "..."` –  Feb 23 '17 at 23:31
  • to @NikxDa, nothing happens, and now that think a little more, Chris G is totally right, I'm making an async request and trying to redirect on the back, which doesn't really makes sense, I guess I'll use the "ok" flag as suggested and redirect on the client, so thanks! –  Feb 23 '17 at 23:37
  • I completely missed that. Embarrassing :D – NikxDa Feb 23 '17 at 23:59

2 Answers2

1

You should handle redirect on the client side once the login is complete. Redirect would work if you're actually visiting the LOGIN_ACTION_URL.

    if(data == "invalid_credentials") {
        $("#alert-wrong-credentials").show(100);
    } else if(data == "ok") {
        // Redirect
        window.location.href = "index_url"; 
    }

Also, there is a similar question here Node.js Page Redirect on AJAX login? With a function call after redirect? .

Community
  • 1
  • 1
subwaymatch
  • 1,020
  • 10
  • 11
1

Ajax calls don't affect the current browser page. You send a request to a server. You get a response. If you want the current browser page to change, then you have to write Javascript that looks at the ajax response and then changes the current browser page by setting:

window.location = someURL;

So, doing a res.redirect() in response to an ajax call will just return a 302 status to the ajax call. That's it. If you want the ajax call to use that as an indicator to change the current browser page, then you have to write code to look for the 302 response and grab the right header from the response and then change window.location. There is no automated way to do that from an Ajax call.

When the browser is requesting a web page for a URL and it gets a 302 when loading a web page, then it will follow the redirect at that point. But, not for Ajax calls. An ajax call just gets you the response, whatever it is and it's up to your code that processes the response to actually do something with it.

jfriend00
  • 683,504
  • 96
  • 985
  • 979