почему-то мой скрипт не запоминает сессию. я логинюсь (/login), но возвращаясь назад на index, в навигационной панели не показывается, что я залогинен, хотя я залогинен и могу редактировать свой профиль, на index.ejs должно быть сообщение вроде “hello, username”,  и если залогинен, предложение с ссылкой на logout, но этого нет. Просмотри код и найди ошибку:

app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');


const connection = mysql.createConnection({
  host: 'localhost',
  user: 'music', // замените на свой логин
  password: 'password', // замените на свой пароль
  database: 'music' // замените на свою базу данных
});

connection.connect((err) => {
  if (err) {
    console.error('Ошибка подключения к базе данных: ', err);
  } else {
    console.log('Подключение к базе данных успешно');
  }
});



app.set("view engine", "ejs");
app.use(express.static("public"));

app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
  secret: "mysecretkey",
  resave: false,
  saveUninitialized: false
}));

const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));

connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
    if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];

// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
    connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
        if (err) {
            console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
            return typeof callback === 'function' && callback(err);
        } else {
            return typeof callback === 'function' && callback(null, result);
        }
    });
}

function getMusicians(callback) {
  connection.query("SELECT * FROM users", (err, result) => {
    if (err) {
      console.error("Ошибка при получении списка музыкантов: ", err);
      return callback(err);
    } else {
      return callback(null, result);
    }
  });
}

// Функция для получения музыканта по id
function getMusicianById(id, callback) {
  connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
    if (err) {
      console.error("Ошибка при получении музыканта с id ${id}: ", err);
      return typeof callback === 'function' && callback(err);
    } else {
      return typeof callback === 'function' && callback(null, result[0]);
    }
  });
}

function requireLogin(req, res, next) {
  if (req.session.musicianId) {
    next();
  } else {
    res.redirect("/login");
  }
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];

// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}

// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});

// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);

// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;

if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}

// Сортировка по score (убывающая)
return scoreB - scoreA;
});

// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}

app.use((req, res, next) => {
  if (req.session.musicianId) {
    getMusicianById(req.session.musicianId, (err, musician) => {
      if (err) {
        console.error("Ошибка при получении current user: ", err);
        res.locals.userLoggedIn = false;
      } else {
        res.locals.musician = musician;
        res.locals.userLoggedIn = true;
        res.locals.username = musician.name;
      }
      next();
    });
  } else {
    res.locals.userLoggedIn = false;
    next();
  }
});

app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });
}
});
});

app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;

connection.query(
"SELECT DISTINCT city FROM users WHERE city LIKE ?",
[searchString + '%'],
(error, results, fields) => {
if (error) {
console.error("Ошибка выполнения запроса: ", error);
res.status(500).send("Ошибка выполнения запроса");
} else {
const cities = results.map(row => row.city);
res.json(cities);
}
}
);
});

app.get("/register", (req, res) => {
  if (req.session.musicianId) {
    const musician = getMusicianById(req.session.musicianId);
    res.redirect("/profile/" + musicianId);
  } else {
	  
	  
	  
    res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
  }
});

app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {

// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login,
};

if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}

connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});

app.get("/profile/:id", (req, res) => {
    getMusicianById(parseInt(req.params.id), (err, musician) => {
        if (err) {
            console.error("Ошибка при получении музыканта: ", err);
            res.status(500).send("Ошибка при получении данных");
        } else {
            if (musician) {
                getMusicianTracks(musician.id, (err, tracks) => {
                    if(err) {
                        console.error("Ошибка при получении треков для профиля: ", err);
                        res.status(500).send("Ошибка при получении данных");
                    } else {
                        res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
                    }
                });
            } else {
                res.status(404).send("Musician not found");
            }
        }
    });
});

app.get("/login", (req, res) => {
  res.render("login");
});

app.post("/login", (req, res) => {
  connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
      if (err) {
        console.error("Ошибка при входе: ", err);
        res.status(500).send("Ошибка при входе");
      } else {
        if (result.length > 0) {
          req.session.musicianId = result[0].id;
          res.redirect("/profile/" + result[0].id);
        } else {
          res.render("login", { error: "Invalid login or password" });
        }
      }
    }
);
});

app.get("/logout", (req, res) => {
  req.session.destroy();
  res.redirect("/");
});

app.get('/search', (req, res) => {
  let query = req.query.query || '';
  const role = req.query.role || '';
  const city = req.query.city || '';
  const genre = req.query.genre || '';

  if (query || role || city || genre) {
    search(query, role, city, genre, (err, musicians) => {
      if (err) {
        res.status(500).send("Ошибка при выполнении поиска");
      } else {
        app.locals.JSON = JSON;
        res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
      }
    });
  } else {
    // Use the getMusicians function instead of reading from musicians.json
    getMusicians((err, musiciansList) => {
      if (err) {
        res.status(500).send("Ошибка при получении списка музыкантов");
      } else {
        const musicians = musiciansList.map(musician => {
          return {
            name: musician.name,
            genre: musician.genre,
            originalName: musician.name,
            profileLink: `/profile/${musician.id}`,
            thumbnail: musician.thumbnail,
            soundcloud: musician.soundcloud,
            role: musician.role,
            city: musician.city
          };
        });

        app.locals.JSON = JSON;
        res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
      }
    });
  }
});


app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
}
});
});





app.post("/profile/:id/edit", requireLogin, (req, res) => {
const musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});

//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, async (req, res) => {
    const musicianId = req.session.musicianId;
    if (!req.files) {
        res.status(400).send("No files were uploaded.");
        return;
    }
    const trackFile = req.files.track;
    if (!trackFile) {
        res.status(400).send("No track file was uploaded.");
        return;
    }
	
	if (trackFile && !trackFile.name.endsWith(".mp3")) {
res.status(400).send("Only .mp3 files can be uploaded.");
return;
}

// Set a maximum file size of 10MB for uploaded files
const maxSizeInBytes = 10000000; // 10MB
if (trackFile && trackFile.size > maxSizeInBytes) {
res.status(400).send("File size exceeds 10MB limit.");
return;
}
    const trackFilename = "track_" + musicianId + "" + trackFile.name;
	const tmpPath = './public/tracks/tmp_' + trackFilename;
    trackFile.mv("./public/tracks/" + trackFilename);

    const title = req.body.title;
    const album_title = req.body.albumTitle;

    const track = {
        musician_id: musicianId,
        title,
        album_title,
        filename: trackFilename,
    };

    if (req.files.image) {
        const imageFile = req.files.image;
        const imageFilename = "image" + musicianId + "_" + imageFile.name;
        imageFile.mv("./public/img/" + imageFilename);
        track.image_filename = imageFilename;
    }

    connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
        if (err) {
            console.error("Ошибка при добавлении трека: ", err);
            res.status(500).send("Ошибка при добавлении трека");
        } else {
            res.redirect("/profile/" + musicianId);
        }
    });
});

function isValidSoundCloudUrl(url) {
  return url.startsWith('https://soundcloud.com/');
}

app.listen(3000, () => {
  console.log("Server started on port 3000");
});

index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta content="width=device-width, initial-scale=1.0" name="viewport">
	<meta content="ie=edge" http-equiv="X-UA-Compatible">
	<script src="/jquery/dist/jquery.min.js"></script>
    <script src="/jquery-ui/dist/jquery-ui.min.js"></script>
	<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
	<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
	<link href="/css/main.css" rel="stylesheet">
	<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
	<link href="/jquery-ui/themes/base/all.css" rel="stylesheet">
	
	<title>Home</title>
</head>
<body>
	<header class="header">
		<nav class="navbar navbar-expand-lg navbar-light bg-light">
			<div class="container">
				<a class="navbar-brand" href="/">
					<img src="/img/logo.png" alt="My Musician Site">
				</a>
				<button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button">
					<span class="navbar-toggler-icon"></span>
				</button>
				<div class="collapse navbar-collapse" id="navbarNav">
					<ul class="navbar-nav ml-auto">
						<li class="nav-item">
							<a class="nav-link" href="#find-musicians">Find Musicians</a>
						</li>
						<li class="nav-item">
							<a class="nav-link" href="/register"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a>
						</li>
						<li class="nav-item">
							<a class="nav-link" href="/login"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
						</li>
					</ul>
				</div>
			</div>
		</nav>
		<div class="hero">
			<div class="container">
				<h1 class="hero-title">Find the Perfect Musician for Your Band or Project</h1>
				<p class="hero-subtitle">Join our community today and connect with talented musicians from around the world.</p>
				<a class="btn btn-primary btn-lg" href="/register">Register Now</a>
			</div>
		</div>
	</header>
	<main class="main">
		<section class="section section-search" id="find-musicians">
			<div class="container">
				<h2 class="section-title"><i class="fa fa-search" aria-hidden="true"></i> Find Musicians</h2>
				<form class="form-search" action="/search" method="get">
					<div class="form-group">
						<label for="role"><i class="fa fa-users" aria-hidden="true"></i> Role:</label> 
						<select class="form-control" id="role" name="role">
							<option value="">All</option>
							<option value="Band">Band</option>
							<option value="Artist">Artist</option>
						</select>
					</div>
					
					<div class="form-group">
  <label for="genre">Search by genre:</label>
  <select class="form-control" id="genre" name="genre">
    <option value="">All</option>
  </select>
</div>
<div class="form-group">
						<label for="city"><i class="fa fa-map-marker" aria-hidden="true"></i> Location:</label> 
						<input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value="">
					</div>
					<button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
				</form>
			</div>
		</section>
		<!-- последние зарегистрированные пользователи -->
		<section class="musicians">
  <div class="container">
    <h2>Find Musicians</h2>
    <div class="row">
      <% musicians.forEach(function(musician) { %>
        <div class="col-lg-4 col-md-6 col-sm-12">
          <div class="musician-card">
            <div class="musician-info">
              <h3><%= musician.name %></h3>
              <p><strong>Genre:</strong> <%= musician.genre %></p>
              <p><strong>Location:</strong> <%= musician.location %></p>
            </div>
            <div class="musician-link">
              <a href="/musicians/<%= musician.id %>">View profile</a>
            </div>
          </div>
        </div>
      <% }); %>
    </div>
  </div>
</section>
		<!-- end -->
	</main>
	<footer class="footer">
		<div class="container">
			<p class="text-center mb-0">My Musician Site &copy; 2023</p>
		</div>
	</footer>
	
	
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
	
	
    
    
	<script>
	$("#city").autocomplete({
    source: '/autocomplete/cities',
    minLength: 1,
  });

  const queryInput = document.querySelector("#query");
  const roleInput = document.querySelector("#role");
  const cityInput = document.querySelector("#city");

  queryInput.value = "<%= query %>";
  roleInput.value = "<%= role %>";
  cityInput.value = cityInput.getAttribute('data-value');

  const query = queryInput.value;
  const role = roleInput.value;
  const city = cityInput.value;
	</script>
	<script>
const genres = ["Rock", "Pop", "Jazz", "Blues", "Country"];
const genreSelect = document.querySelector("#genre");
genres.forEach((genre) => {
  const option = document.createElement("option");
  option.value = genre;
  option.text = genre;
  genreSelect.appendChild(option);
});
</script>
  </body>
</html>