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.