简体   繁体   中英

Unable to redirect in express with Node JS

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM