0
我目前正在編寫一個需要用戶認證的應用程序。當您登錄到應用程序時,節點服務器應該將用戶重定向到主頁面。不幸的是,我在嘗試這樣做時遇到了問題。Node.js表示res.redirect不工作
這是我在Node.js的代碼:
//import necessary modules
var path = require("path");
var http = require("http");
var express = require("express");
var session = require("express-session");
var port = 8080;
var app = express();
var conString = "postgres://postgres:[email protected]:5432/db_invoice_kuga";
/**
* Middleware components.
* The session middleware is used to create sessions for
* user authentication.
* The static middleware is used to serve
* the static file in the frontend folder.
*/
//use sessions for authentication
app.use(session({
secret: "2C44-4D44-WppQ38S",
resave: true,
saveUninitialized: true
}));
//check authentication
app.use(function(req, res, next) {
if(req.session && req.session.user) {
next();
} else {
if(req.url.indexOf("/login/") === -1 && req.url.indexOf("/loginPage") === -1) {
res.redirect("/loginPage");
} else {
next();
}
}
});
//static middleware
app.use(express.static(__dirname + "/frontend"));
/**
* Routes define the endpoints for the application.
* There is a specific file for customer routes, invoice routes, ...
*/
//include routes
require("./routes/routesCustomer.js")(app, conString);
//login and logout routes
app.get("/loginPage", function(req, res) {
res.sendFile(path.join(__dirname, "frontend", "login.html"));
});
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "frontend", "index.html"));
});
/**
* Logs the user in.
* @name /login/:username/:password
* @param username (obligatory)
* @param password (obligatory)
*/
app.get("/login/:username/:password", function(req, res) {
var username = req.params.username;
var password = req.params.password;
if(username === "Daniel" && password === "test") {
req.session.user = "Daniel";
res.redirect("/");
} else {
res.status(400).json({
"loggedin": false
});
}
});
/**
* Logs the user out.
* @name /logout
*/
app.get("/logout", function(req, res) {
req.session.destroy();
res.redirect("/loginPage");
});
/**
* Bind the server to the port and
* start the application.
*/
//create the server and bind it to the port
http.createServer(app).listen(port, function() {
console.log("Server listening on port " + port);
});
我的問題是路由 「/登錄/:用戶名/:密碼」。那裏「res.redirect('/')」不起作用。雖然重定向()在其他路線工作得很好...
有沒有人有一個想法是什麼可能是錯的?也許還有更好的方法來做用戶驗證。我會很感激建議:)
非常感謝您提前。 丹尼爾
「不工作」是什麼意思?怎麼了?錯誤?用戶最後回到'/ loginPage'?客戶端是否收到來自服務器的任何響應?一些簡單的調試步驟需要先完成,然後在這裏共享這些步驟的結果。 – jfriend00
偶然的,你是否在通過AJAX調用「登錄」路線? - 我只是繼續並假設它是。您無法通過AJAX調用重定向服務器 - 必須在客戶端上完成 – tymeJV
非常感謝您的答覆。 –