Я создам для вас веб-сайт туристического агентства с API-сервером на Node.js и базой данных MySQL. Мы также интегрируем внешние API для получения информации о погоде и курсах валют.
const app = express(); const PORT = process.env.PORT || 3000;
// Middleware app.use(cors()); app.use(express.json());
// Подключение к MySQL const pool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, waitForConnections: true, connectionLimit: 10, queueLimit: 0 });
// Проверка соединения с БД pool.getConnection() .then(conn => { console.log('Connected to MySQL database'); conn.release(); }) .catch(err => { console.error('Error connecting to MySQL:', err); });
// API для туров app.get('/api/tours', async (req, res) => { try { const [rows] = await pool.query('SELECT * FROM tours'); res.json(rows); } catch (err) { console.error(err); res.status(500).json({ error: 'Database error' }); } });
// API для погоды (интеграция с внешним API)
app.get('/api/weather/:city', async (req, res) => {
try {
const { city } = req.params;
const response = await axios.get(
https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.WEATHER_API_KEY}&units=metric&lang=ru
);
res.json({
city: response.data.name,
temp: response.data.main.temp,
description: response.data.weather[0].description
});
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Weather API error' });
}
});
// API для курсов валют (интеграция с внешним API)
app.get('/api/currency', async (req, res) => {
try {
const response = await axios.get(
https://api.exchangerate-api.com/v4/latest/USD
);
res.json({
usd: response.data.rates.RUB,
eur: response.data.rates.EUR
});
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Currency API error' });
}
});
// Запуск сервера
app.listen(PORT, () => {
console.log(Server is running on port ${PORT});
});
</file>
<section id="contact">
<h2>Контакты</h2>
<p>Email: info@travel-agency.com</p>
<p>Телефон: +7 (123) 456-78-90</p>
</section>
<section id="contact">
<h2>Контакты</h2>
<p>Email: info@travel-agency.com</p>
<p>Телефон: +7 (123) 456-78-90</p>
</section>
header { background: #0078d7; color: white; padding: 1rem; text-align: center; }
#weather, #currency { margin: 1rem 0; font-size: 1.2rem; }
main { padding: 2rem; }
#tours-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1rem; }
.tour-card { border: 1px solid #ddd; border-radius: 5px; padding: 1rem; transition: transform 0.3s; }
.tour-card:hover { transform: translateY(-5px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
.tour-card h3 { margin-top: 0; color: #0078d7; }
.tour-card .price { font-weight: bold; color: #2e7d32; font-size: 1.2rem; } </file>
<file path="public/script.js"> document.addEventListener('DOMContentLoaded', async () => { // Загрузка туров try { const response = await fetch('/api/tours'); const tours = await response.json(); renderTours(tours); } catch (err) { console.error('Error loading tours:', err); }// Загрузка погоды (по умолчанию Москва) loadWeather('Moscow');
// Загрузка курсов валют loadCurrency(); });
function renderTours(tours) {
const toursList = document.getElementById('tours-list');
toursList.innerHTML = tours.map(tour => <div class="tour-card"> <h3>${tour.title}</h3> <p>${tour.description}</p> <p>Страна: ${tour.country}</p> <p>Даты: ${tour.start_date} - ${tour.end_date}</p> <p class="price">Цена: ${tour.price} руб.</p> </div> ).join('');
}
async function loadWeather(city) {
try {
const response = await fetch(/api/weather/${city});
const weather = await response.json();
document.getElementById('weather').innerHTML = Погода в ${weather.city}: ${weather.temp}°C, ${weather.description} ;
} catch (err) {
console.error('Error loading weather:', err);
}
}
async function loadCurrency() {
try {
const response = await fetch('/api/currency');
const currency = await response.json();
document.getElementById('currency').innerHTML = Курсы валют: 1 USD = ${currency.usd.toFixed(2)} RUB, 1 EUR = ${currency.eur.toFixed(2)} RUB ;
} catch (err) {
console.error('Error loading currency:', err);
}
}
</file>
USE travel_agency;
CREATE TABLE IF NOT EXISTS tours ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, description TEXT, country VARCHAR(100) NOT NULL, start_date DATE, end_date DATE, price DECIMAL(10, 2) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
INSERT INTO tours (title, description, country, start_date, end_date, price) VALUES ('Отдых в Турции', 'Отдых на лучших пляжах Анталии с экскурсиями', 'Турция', '2023-07-15', '2023-07-25', 45000.00), ('Горнолыжный курорт в Сочи', 'Горнолыжный курорт Красная Поляна с проживанием в 5* отеле', 'Россия', '2023-12-20', '2023-12-30', 60000.00), ('Экскурсия по Европе', 'Тур по 5 странам Европы с посещением главных достопримечательностей', 'Европа', '2023-09-01', '2023-09-15', 85000.00); </file> </project>
db/schema.sqlnpm install.env и заполните его данными (пример в .env.example)npm start (или npm run dev для разработки)http://localhost:3000