0
현재 사용자 인증이 필요한 응용 프로그램을 프로그래밍 중입니다. 응용 프로그램에 로그인하면 노드 서버가 사용자를 기본 페이지로 리디렉션해야합니다. 불행히도, 나는 그것을 시도 할 때 문제에 직면하고있다.Node.js res.redirect가 작동하지 않음
//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);
});
내 문제는 경로 ": 사용자 이름/: 비밀번호/로그인 /"입니다 :
여기 Node.js를 내 코드입니다. 거기에 "res.redirect ('/')"가 작동하지 않습니다. redirect()가 다른 경로에서도 정상적으로 작동하지만 ...
아무도 잘못 될 수있는 아이디어가 있습니까? 어쩌면 사용자 인증을 수행하는 더 좋은 방법이있을 수도 있습니다. 나는 제안을 바랄 것이다 :
대단히 감사합니다. 다니엘
이 내 코드는 지금과 같은 모습입니다
"작동하지 않음"은 무엇을 의미합니까? 무슨 일이야? 오류? 사용자가 다시 끝나고'/ loginPage'? 클라이언트가 서버로부터 응답을 수신합니까? 몇 가지 간단한 디버깅 단계를 먼저 수행하고 여기에서 공유 한 결과를 수행해야합니다. – jfriend00
우연히, AJAX 호출을 통해'로그인 '경로를 고수하고 있습니까? - 아쉽다. AJAX 호출에서 서버 리디렉션을 수행 할 수 없습니다. 클라이언트에서 수행해야합니다. – tymeJV
답변 해 주셔서 감사합니다. –