Вот весь код:
index.js:
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import postgres from "./db.js";

import authRoutes from "./route/authRoutes.js";
import projectRoutes from "./route/projectRoutes.js";

const port = process.env.PORT ?? 5000;

(async function connectToDatabase() {
try {
await postgres.raw("SELECT 1+1 AS result");
console.log("Successful connection to database");
} catch (error) {
console.error("Error connecting to database:", error);
}
})();

dotenv.config();

const app = express();
app.listen(port, () => console.log(Server is running on port: ${port}));

app.use(cors());
app.use(express.json());
app.use("/img", express.static("./img"));

app.get("/api/test", (_, res) => {
res.json({ message: "Server is connected to frontend" });
});

app.use("/api", authRoutes);
app.use("/api", projectRoutes);

app.use((err, req, res, next) => {
console.error("Ошибка:", err);
res.status(500).json({ message: "Internal server error" });
});

authRoutes:
import express from "express";
import {
login,
refreshToken,
logout,
signup,
} from "../controller/authController.js";
import { validateSignup } from "../middleware/validationMiddleware.js";

const router = express.Router();

router.post("/login", login);
router.post("/token", refreshToken);
router.post("/logout", logout);
router.post("/signup", validateSignup, signup);

export default router;

projectRoutes:
import express from "express";
import { getCards } from "../controller/projectController.js";
import { authenticateToken } from "../middleware/authMiddleware.js";

const router = express.Router();

router.get("/cards", authenticateToken, getCards);

export default router;

authController:
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
import { findUserByUsername, createUser } from "../model/userModel.js";

dotenv.config();

const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET;
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET;

let refreshTokens = [];

export const login = async (req, res) => {
const { username, password } = req.body;

try {
const user = await findUserByUsername(username);


if (!user) {
  return res.status(401).json({ message: "Неверные учетные данные" });
}

const isPasswordValid = await bcrypt.compare(password, user.password);

if (!isPasswordValid) {
  return res.status(401).json({ message: "Неверные учетные данные" });
}

const userPayload = {
  userId: user.id,
  username: user.username,
};

const accessToken = jwt.sign(userPayload, ACCESS_TOKEN_SECRET, {
  expiresIn: "30s",
});

const refreshToken = jwt.sign(userPayload, REFRESH_TOKEN_SECRET, {
  expiresIn: "2m",
});
console.log("Generated Refresh Token:", refreshToken);
refreshTokens.push(refreshToken);
console.log("Current Refresh Tokens:", refreshTokens);

res.status(200).json({
  accessToken,
  refreshToken,
  user: {
    userId: user.id,
    username: user.username,
  },
});
} catch (error) {
console.error("Ошибка входа:", error);
}
};

export const refreshToken = (req, res) => {
const { refreshToken } = req.body;

console.log("Received Refresh Token for Refresh:", refreshToken);
console.log("Valid Refresh Tokens:", refreshTokens.includes(refreshToken));
if (!refreshToken)
return res.status(401).json({ message: "Токен не предоставлен" });
if (!refreshTokens.includes(refreshToken))
return res.status(403).json({ message: "Недействительный токен" });

jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.status(403).json({ message: "Недействительный токен" });


const userPayload = {
  userId: user.userId,
  username: user.username,
};

const newAccessToken = jwt.sign(userPayload, ACCESS_TOKEN_SECRET, {
  expiresIn: "30s",
});

res.json({ accessToken: newAccessToken });
});
};

export const logout = (req, res) => {
const { refreshToken } = req.body;
refreshTokens = refreshTokens.filter((token) => token !== refreshToken);
res.status(200).json({ message: "Выход из системы выполнен" });
};

export const signup = async (req, res) => {
const { firstName, lastName, username, password, age } = req.body;

try {
const existingUser = await findUserByUsername(username);


if (existingUser) {
  return res
    .status(400)
    .json({ errors: { username: "Имя пользователя уже занято." } });
}

const hashedPassword = await bcrypt.hash(password, 12);

await createUser({
  firstName,
  lastName,
  username,
  password: hashedPassword,
  age,
});

res.status(201).json({ message: "Регистрация прошла успешно" });
} catch (error) {
console.error("Ошибка во время регистрации:", error);
res.status(500).json({ message: "Ошибка сервера" });
}
};

userModel:
import postgres from "../db.js";

export const findUserByUsername = (username) => {
return postgres("users").where({ username }).first();
};

export const createUser = (userData) => {
return postgres("users").insert(userData);
};

projectController:
// controller/projectController.js
import dotenv from "dotenv";
import { getProjects } from "../model/projectModel.js";

dotenv.config();

export const getCards = async (req, res) => {
try {
const userId = req.user.userId;
const username = req.user.username;
console.log(
Пользователь ${username} (ID: ${userId}) запрашивает карточки.
);


const searchTerm = req.query.search ? req.query.search.toLowerCase() : "";

const projects = await getProjects(searchTerm);

const apiBaseUrl =
  process.env.REACT_APP_API_BASE_URL ??
  "https://server-ancient-grass-9030.fly.dev";
const projectsWithImgSrc = projects.map((project) => ({
  ...project,
  imgSrc: `${apiBaseUrl}${project.img_src}`,
}));

res.json(projectsWithImgSrc);
} catch (error) {
console.error("Error getting projects:", error);
res.status(500).json({ error: "Cannot get projects" });
}
};

projectModel:
import postgres from "../db.js";

export const getProjects = (searchTerm) => {
let query = postgres("projects").select("*");

if (searchTerm) {
query = query.where(function () {
this.whereRaw("LOWER(title) LIKE ?", [%${searchTerm}%]).orWhereRaw(
"LOWER(description) LIKE ?",
[%${searchTerm}%]
);
});
}

return query;
};

authMiddleware:
import jwt from "jsonwebtoken";
import dotenv from "dotenv";

dotenv.config();

const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET;

export const authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];

if (!token) {
return res.status(401).json({ message: "Токен не предоставлен" });
}

jwt.verify(token, ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
if (err.name === "TokenExpiredError") {
console.log("JWT валидация не удалась: токен истёк");
return res.status(401).json({ message: "Токен истёк" });
}
console.log("JWT валидация не удалась:", err);
return res.status(401).json({ message: "Неверный токен" });
}


req.user = user;
next();
});
};




Перепиши все логи на английский, удали все комментарии, если она будут