简体   繁体   English

无法使用Node JS在Express中重定向

[英]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!". 我正在学习Node.js + MongoDB和其他一些相关工具的基础知识,但是我陷入了一个简单的登录屏幕中,目标是一旦提供了正确的凭据,便重定向到index.html有一个文字“ welcome!”。 I've taken a look at different places (official API, tutorials, this page, etc.) but can't see my error yet. 我看过不同的地方(官方API,教程,此页面等),但还看不到我的错误。

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: 尝试不存在的凭据时,我可以成功返回错误字符串“ invalid_credentials”,输入正确的凭据时,我可以看到用户数据:

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

but I'm unable to redirect to the index.html page. 但我无法重定向到index.html页面。

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. 如果您实际上是在访问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? 另外,这里还有一个类似的问题,即AJAX登录上的Node.js页面重定向? With a function call after redirect? 重定向后使用函数调用? .

Ajax calls don't affect the current browser page. Ajax调用不会影响当前的浏览器页面。 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: 如果要更改当前浏览器页面,则必须编写可查看ajax响应的Javascript,然后通过设置以下内容来更改当前浏览器页面:

window.location = someURL;

So, doing a res.redirect() in response to an ajax call will just return a 302 status to the ajax call. 因此,响应ajax调用执行res.redirect()只会将302状态返回给ajax调用。 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 . 如果希望ajax调用将其用作指示符来更改当前浏览器页面,则必须编写代码以查找302响应并从响应中获取正确的标头,然后更改window.location There is no automated way to do that from an Ajax call. 没有自动的方法可以通过Ajax调用来做到这一点。

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. 当浏览器正在请求网页的URL并在加载网页时得到302时,它将遵循重定向。 But, not for Ajax calls. 但是,不适用于Ajax调用。 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. 一个ajax调用只是获取响应,无论响应是什么,它都取决于处理响应以实际对其进行处理的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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