簡體   English   中英

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

[英]Unable to redirect in express with Node JS

我正在學習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頁面。

登錄完成后,您應該在客戶端上處理重定向。 如果您實際上是在訪問LOGIN_ACTION_URL,則重定向將起作用。

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

另外,這里還有一個類似的問題,即AJAX登錄上的Node.js頁面重定向? 重定向后使用函數調用?

Ajax調用不會影響當前的瀏覽器頁面。 您將請求發送到服務器。 您得到回應。 如果要更改當前瀏覽器頁面,則必須編寫可查看ajax響應的Javascript,然后通過設置以下內容來更改當前瀏覽器頁面:

window.location = someURL;

因此,響應ajax調用執行res.redirect()只會將302狀態返回給ajax調用。 而已。 如果希望ajax調用將其用作指示符來更改當前瀏覽器頁面,則必須編寫代碼以查找302響應並從響應中獲取正確的標頭,然后更改window.location 沒有自動的方法可以通過Ajax調用來做到這一點。

當瀏覽器正在請求網頁的URL並在加載網頁時得到302時,它將遵循重定向。 但是,不適用於Ajax調用。 一個ajax調用只是獲取響應,無論響應是什么,它都取決於處理響應以實際對其進行處理的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM