При загрузке аудиофайла в профиле в модальном окне профиля пользователя ничего не происходит. Я жму “upload track” и ничего не происходит. База данных tracks не пополняется, папка с треками тоже пустая, как и картинки для альбома не загружаются. проанализируй код, в первую очередь app.js, исправь проблему. так же я получаю ошибку 10:165 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at 10:165:5

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);
      } else {
        res.locals.musician = musician;
        res.locals.userLoggedIn = true;
        res.locals.username = musician.name;
      }
    });
  } 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/" + musician.id);
  } 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, (req, res) => {
    const musicianId = parseInt(req.params.id);
    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;
    }
    const trackFilename = "track_" + musicianId + "" + trackFile.name;
    trackFile.mv("./public/tracks/" + trackFilename);

    const title = req.body.title;
    const albumTitle = req.body.albumTitle || '';

    const track = {
        musician_id: musicianId,
        title,
        albumTitle,
        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");
});
profile.ejs:
<!DOCTYPE html>
<html>
  <head>
    <title><%= musician.name %> - Musician Profile</title>
	<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
	
	<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
 
  <!-- Popper.js -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <!-- Bootstrap JS -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  
  <!-- Custom CSS -->
  <link rel="stylesheet" href="/css/main.css" />


  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-md-3">
          <img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200">
        </div>
        <div class="col-md-8">
          <h1><%= musician.name %></h1>
          <p><strong>Role:</strong> <%= musician.role %></p>
          <p><strong>Genre:</strong> <%= musician.genre %></p>
          <% if (musician.role === 'Artist' && musician.instrument) { %>
            <p><strong>Instrument:</strong> <%= musician.instrument %></p>
          <% } %>
          <p><strong>Location:</strong> <%= musician.city %></p>
          <p><strong>Bio:</strong> <%= musician.bio %></p>
		  <!-- users' music -->
		  <h3>Tracks:</h3>
    <ul>
        <% tracks.forEach(track => { %>
            <li>
                <%= track.title %> (<%= track.album_title || "No Album" %>)
                <audio controls>
                    <source src="/tracks/<%= track.filename %>" type="audio/mpeg">
                </audio>
                <img src="/img/<%= track.image_filename || 'default-track-image.jpg' %>" alt="<%= track.title %>" width="200" height="200">
            </li>
        <% }); %>
    </ul>
          <% if (musician.soundcloud) { %>
            <div class="embed-responsive embed-responsive-16by9">
              <iframe class="embed-responsive-item" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
            </div>
          <% } %>
          <% if (musician.soundcloud1) { %>
            <div class="embed-responsive embed-responsive-16by9">
              <iframe class="embed-responsive-item" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud1 %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
            </div>
			
          <% } %>
          <% if (userLoggedIn && username === musician.name) { %>
            <button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button>
            <div id="edit-profile-modal" class="modal fade">
              <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                  <div class="modal-header">
                    <h4 class="modal-title">Edit Profile</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                  </div>
                  <div class="modal-body">
                    <form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
                      <div class="form-group">
                        <label for="name">Name:</label>
                        <input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control">
                      </div>
                      <div class="form-group">
                        <label for="role">Role:</label>
                        <select id="role" name="role" class="form-control">
                          <option value="">Select a role</option>
                          <option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option>
                          <option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option>
                        </select>
                      </div>
                      <div class="form-group">
                        <label for="genre">Genre:</label>
                        <select id="genre" name="genre" class="form-control">
                          <option value="">Select a genre</option>
                          <option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option>
                         <option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option>
                          <option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option>
                          <option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option>
                          <option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option>
                          <option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option>
                        </select>
                      </div>
                      <% if (musician.role === 'Artist') { %>
                        <div class="form-group">
                          <label for="instrument">Instrument:</label>
                          <input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control">
                        </div>
                      <% } %>
                      <div class="form-group">
                        <label for="city">Location:</label>
                        <input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control">
                      </div>
                      <div class="form-group">
                        <label for="bio">Bio:</label>
                        <textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea>
                      </div>
                      <div class="form-group">
                        <label for="thumbnail">Thumbnail:</label>
                        <input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file">
                      </div>
					  <!-- загрузка музла -->
					  
    
<div>
    <h2>Upload a new track:</h2>
    <form id="upload-form" enctype="multipart/form-data" onsubmit="submitForm(event)">
        <div class="form-group">
            <label for="track">Track file:</label>
            <input type="file" id="track" name="track" accept="audio/*" class="form-control-file" required>
        </div>
        <div class="form-group">
            <label for="title">Track title:</label>
            <input type="text" id="title" name="title" class="form-control" required>
        </div>
        <div class="form-group">
            <label for="albumTitle">Album title:</label>
            <input type="text" id="albumTitle" name="albumTitle" class="form-control">
        </div>
        <div class="form-group">
            <label for="image">Track image:</label>
            <input type="file" id="image" name="image" accept="image/*" class="form-control-file">
        </div>
        <button type="submit" class="btn btn-primary">Upload Track</button>
    </form>
	
</div>
					  <!-- конец -->
                      <div class="form-group">
                        <label for="soundcloud">Soundcloud Track:</label>
                        <input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control">
                      </div>
                      <div class="form-group">
                        <label for="soundcloud1">Soundcloud Track 2:</label>
                        <input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control">
                      </div>
                      <button type="submit" class="btn btn-primary">Save Changes</button>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          <% } %>
        </div>
      </div>
    </div>
  
	
	<script>
  function submitForm(event) {
    event.preventDefault();
    const form = document.getElementById("upload-form");
    const formData = new FormData(form);
    
    fetch("/profile/<%= musician.id %>/upload", {
      method: "POST",
      body: formData,
    })
      .then((response) => {
        if (response.ok) {
          // если запрос прошел успешно - обновляем страницу
          location.reload();
        } else {
          // если что-то пошло не так - выводим сообщение об ошибке
          alert("Error uploading track");
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error uploading track");
      });
  }

  // Заменяем элемент формы с кнопкой "submit" на обработчик события "submit"
  document
    .getElementById("upload-form")
    .addEventListener("submit", submitForm);
</script>