Не загружает CSS и JS файлы при запуске сервера на NodeJS
Серверная часть
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const app = express();
const port = 3000;
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Обслуживание статических файлов
app.use(express.static(path.join(__dirname, '..', 'src')));
app.use(express.static(path.join(__dirname, '..', 'inputs')));
// Маршрут для корневого URL
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'src', 'index.html'));
});
app.get('/inputs', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'inputs', 'index.html'));
})
// Переменная для хранения числа
let savedNumber = null;
// Маршрут для сохранения числа с телефона
app.post('/api/save-number', (req, res) => {
const number = req.body.number;
if (number && !isNaN(number)) {
savedNumber = number;
res.send({ success: true, message: "Число сохранено!" });
} else {
res.status(400).send({ success: false, message: "Некорректное число" });
}
});
// Маршрут для получения числа с компьютреа
app.get('/api/get-number', (req, res) => {
if (savedNumber !== null) {
res.json({ success: true, number: savedNumber });
} else {
res.status(404).send({ success: false, message: "Число не найдено" });
}
});
// Запуск сервера
app.listen(port, () => {
console.log(`Сервер запущен на http://localhost:${port}`);
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Generator</title>
<link rel="stylesheet" href="/src/style.css">
</head>
<body>
<div class="main">
<div class="h-container">
<h1>Случайное число:</h1>
<input type="submit" id="generator" name="generator" required value="Сгенерировать">
</div>
<div class="input-container">
<label for="numberInput">Введите число:</label>
<input type="number" id="numberInput" min="0" max="200000" value="0">
</div>
</div>
<script src="/src/script.js"></script>
</body>
</html>
При запуске сервера почему то не загружает CSS и JS файлы, хотя если запускать саму html страницу, то все прекрасно работает, поэтому вся проблема в сервере и скорее всего в этих строках кода:
// Обслуживание статических файлов
app.use(express.static(path.join(__dirname, '..', 'src')));
app.use(express.static(path.join(__dirname, '..', 'inputs')));
// Маршрут для корневого URL
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'src', 'index.html'));
});
app.get('/inputs', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'inputs', 'index.html'));
})
Но, я не вижу здесь ошибки, уже облазил все форумы и не могу понять где она.
Вот кстати ошибки, которые выводятся в консоли в инструментах разработчика при запуске сервера:
Refused to apply style from 'http://localhost:3000/src/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. script.js:1
Failed to load resource: the server responded with a status of 404 (Not Found)localhost/:1
Refused to execute script from 'http://localhost:3000/src/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. localhost/:1 Refused to apply style from 'http://localhost:3000/src/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.