无法使用Node JS

时间:2017-02-23 23:24:10

标签: javascript node.js mongodb

我正在学习Node.js + MongoDB以及其他一些相关工具的基础知识,但是我陷入了一个简单的登录界面,一旦获得了正确的凭据,我的目标就是重定向到index.html只有一个文本" welcome!"。我已经查看了不同的地方(官方API,教程,此页面等),但无法查看我的错误。

这是我的服务器:

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

这是在登录视图中完成的:

$.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);
});

我可以成功返回错误字符串" invalid_credentials"在尝试不存在的凭据时,我可以在输入正确的凭据时看到用户数据:

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

但我无法重定向到index.html页面。

2 个答案:

答案 0 :(得分:1)

登录完成后,您应该在客户端处理重定向。如果您实际访问LOGIN_ACTION_URL,重定向将起作用。

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

另外,这里有一个类似的问题Node.js Page Redirect on AJAX login? With a function call after redirect?

答案 1 :(得分:1)

Ajax调用不会影响当前的浏览器页面。您向服务器发送请求。你得到了答复。如果您希望更改当前浏览器页面,则必须编写查看ajax响应的Javascript,然后通过设置更改当前浏览器页面:

window.location = someURL;

因此,响应ajax调用执行res.redirect()只会返回302状态到ajax调用。就是这样。如果您希望ajax调用将其用作更改当前浏览器页面的指示符,则必须编写代码以查找302响应并从响应中获取正确的标题,然后更改window.location。从Ajax调用中没有自动化的方法。

当浏览器请求URL的网页并且在加载网页时获得302时,它将遵循该点的重定向。但是,不适用于Ajax调用。 ajax调用只会让你获得响应,无论它是什么,它都取决于你的代码处理响应以实际执行某些操作。