我學習的Node.js + MongoDB的和其他一些相關工具的基礎知識,但我被困在一個簡單的登錄屏幕,我提出,我們的目標是,一旦正確的憑證被重定向到僅包含文本「welcome!」的index.html。我看了一下不同的地方(官方API,教程,這個頁面等),但看不到我的錯誤。無法在快遞重定向與節點JS
這是我的服務器:
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:[email protected]: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頁面。
你正在嘗試使用,如果你正在訪問的網頁只會工作的重定向。但是你通過Ajax請求它。這意味着你必須在客戶端,在'日期==「OK」'塊,重定向使用'document.location.href =「...」' –
到@NikxDa,什麼都不會發生,而現在覺得有點更重要的是,克里斯G是完全正確的,我做了一個異步請求,並試圖在後面重定向,這沒有什麼意義,我想我會按照建議使用「ok」標誌並在客戶端重定向,那謝謝啦! – Gustavo
我完全錯過了。尷尬:D – NikxDa