I am writing a training project: client-server on Node JS vanilla js. using Vite.js
is loaded when the server and client are started index.html which downloads the app.js, which is already loading the rest of the pages. The problem is that the js files connected on other pages are not connected.
That is, if I connect the rest of the js files on the page index.html they work, but not the document.getElementById does not work, since other html has not loaded yet.
This is my server:
import express from 'express'
import cors from 'cors'
import { router } from './router/index.js'
import { connectToDatabase } from './db/index.js'
import { success, error, info } from './utils/chalk.js'
import socketController from './socket/socket.js'
import { Server } from 'socket.io'
import http from 'http'
import 'dotenv/config'
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// creating express app/server
const app = express()
const server = http.createServer(app)
const io = new Server(server, {
cors: {
origin: 'http://localhost:3000'
}
})
const port = process.env.PORT || 5000
app.use(express.static(path.join(__dirname, '../client')));
app.get('/', (req, res) => {
res.send('${path.join(__dirname, "../client/index.html")}');
});
// enabling application/json headers
app.use(express.json())
// enabling cors policy
app.use(cors({
origin: process.env.CLIENT_ORIGIN_URI,
methods: ["POST", "PUT", "GET", "DELETE", "OPTIONS"],
}))
// http://localhost:5000
app.use('/api/flights', router.flightRouter)
app.use('/api/passengers', router.passengerRouter)
app.use('/api/airports', router.airportRouter)
app.use('/api/planes', router.planeRouter)
app.use('/api/admins', router.adminRouter)
// socket io connetions
io.on('connection', socketController)
// Connecting to the database
connectToDatabase()
.then(() => console.log(success("[database] [success] Connected to database")))
.catch(() => console.log(error("[database] [error] Doesn't connected to database")))
// starting up the server
server.listen(port, () => {
console.log(success(`[server] [success] Server has been started...
n[server] [success] URL: http://localhost:${port}`))
})
This is index.html
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>URTK Airport Panel</title>
<link rel="stylesheet" href="src/index.css">
<script type="module" src="src/app.js" defer></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
This is app.js
import axios from 'axios';
async function loadPageWithAxios(href) {
try {
const response = await axios.get(href);
return response.data;
} catch (error) {
console.error('Ошибка при загрузке страницы:', error);
throw error;
}
}
// renderApp.js
import AuthPage from './pages/AuthPage/AuthPage.html';
function renderApp() {
const isAuthorized = !!localStorage.getItem('token') &&
!!localStorage.getItem('fullName') &&
!!localStorage.getItem('admin-type');
const rootElement = document.getElementById('root');
let routing;
if (!isAuthorized) {
loadPageWithAxios('src/test.html')
.then(html => {
rootElement.innerHTML = html;
})
.catch(error => {
console.error('Ошибка при загрузке страницы:', error);
});
} else {
loadPageWithAxios(AuthPage)
.then(html => {
rootElement.innerHTML = html;
})
.catch(error => {
console.error('Ошибка при загрузке страницы:', error);
});
}
}
window.onload = renderApp;
this is AuthPage.html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Вход</title>
<link rel="stylesheet" href="/public/css/AuthPage.css">
<script type="text/javascript" src="/admin/public/js/AuthPage.js" defer></script>
</head>
<body>
<div class="auth">
<div class="auth__container" id="authContainer">
<div class="auth__container__header">
<div class="header__company-logo">URTK Airport</div>
<div class="header__container-name">Вход</div>
</div>
<form class='auth__form' id="authForm">
<div class="auth__form__item">
<div class="item__title">Ваше ФИО</div>
<input
type="text"
class="item__input"
id="fullNameInput"
placeholder='Иванов Иван Иванович'
/>
</div>
<div class="auth__form__item">
<div class="item__title">Ваш пароль</div>
<input
type="password"
class="item__input"
id="passwordInput"
placeholder='Пароль'
/>
</div>
<div class="auth__form__item">
<div class="item__title">Секретное слово</div>
<input
type="password"
class="item__input"
id="secretWordInput"
placeholder='Секретное слово'
/>
</div>
<button
class='send-data-button'
type='button'
id="submitButton"
>Войти</button>
</form>
<div id="loadingSpinner" class="hidden">Loading...</div>
</div>
</div>
</body>
</html>
I connected static files in all ways.
I tried to remove Vite from the client.
Nothing helped
Дмитрий Бояркин is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.