Files
login-page/panel-mgmt_backend/server.js

65 lines
1.7 KiB
JavaScript

// static variables and imports
import express from "express";
import {
loginUser,
createUser,
updateUser,
deleteUser,
getAllUsers,
} from "../shared/database.js";
import dotenv from "dotenv";
import path from "path";
import axios from "axios";
import { fileURLToPath } from "url";
const app = express();
dotenv.config();
const port = 4001;
app.use(express.json());
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.set("view engine", "ejs");
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
// -- here comes the main code --
app.get("/", (req, res) => {
res.render("index.ejs", { error: null });
});
app.post("/login", (req, res) => {
const { username, password } = req.body;
const apiUrl = "http://localhost:4002/login";
axios
.post(apiUrl, { username, password })
.then(function (response) {
if (response.data.loginQuery) {
// If login is successful, redirect to the dashboard
res.render("userView.ejs");
} else {
// If login fails, render the login page with an error message
res.status(404).render("index.ejs", { error: response.data.message });
}
})
.catch(function (error) {
console.error("Error during login:", error);
res
.status(500)
.render("index.ejs", { error: "An error occurred during login." });
});
});
// error handling code
app.use((err, req, res, next) => {
// Log the error stack and send a generic error response
console.error(err.stack);
res.status(500).send("Something broke!");
});