JIT
Создание сайта туристического агентства с node js и MySQL
Создайте сайт туристического агентства с API-сервером на node js и базой данных MySQL и интегрируйте другие API

Туристическое агентство с API на Node.js и MySQL

Я создам для вас веб-сайт туристического агентства с API-сервером на Node.js и базой данных MySQL. Мы также интегрируем внешние API для получения информации о погоде и курсах валют.

Структура проекта

  1. Фронтенд: HTML, CSS, JavaScript
  2. Бэкенд: Node.js с Express
  3. База данных: MySQL
  4. Внешние API: Погода и курсы валют
<project id="travel-agency" title="Туристическое агентство"> <file path="package.json"> { "name": "travel-agency", "version": "1.0.0", "description": "API для туристического агентства", "main": "server.js", "scripts": { "start": "node server.js", "dev": "nodemon server.js" }, "dependencies": { "express": "^4.18.2", "mysql2": "^3.6.0", "axios": "^1.6.2", "cors": "^2.8.5", "dotenv": "^16.3.1" }, "devDependencies": { "nodemon": "^3.0.2" } } </file> <file path="server.js"> require('dotenv').config(); const express = require('express'); const mysql = require('mysql2/promise'); const axios = require('axios'); const cors = require('cors');

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>

<file path="public/index.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="styles.css"> </head> <body> <header> <h1>Туристическое агентство "Путешествия"</h1> <div id="weather"></div> <div id="currency"></div> </header> <main> <section id="tours"> <h2>Наши туры</h2> <div id="tours-list"></div> </section>
<section id="contact">
  <h2>Контакты</h2>
  <p>Email: info@travel-agency.com</p>
  <p>Телефон: +7 (123) 456-78-90</p>
</section>
</main> <script src="script.js"></script> </body> </html> </file> <file path="public/styles.css"> body { font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 0; color: #333; }

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>

<file path=".env"> DB_HOST=localhost DB_USER=root DB_PASSWORD=yourpassword DB_NAME=travel_agency WEATHER_API_KEY=your_weather_api_key </file> <file path="db/schema.sql"> CREATE DATABASE IF NOT EXISTS travel_agency;

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>

Инструкции по запуску

  1. Установите MySQL и создайте базу данных, выполнив скрипт из db/schema.sql
  2. Установите зависимости: npm install
  3. Создайте файл .env и заполните его данными (пример в .env.example)
  4. Запустите сервер: npm start (или npm run dev для разработки)
  5. Откройте в браузере http://localhost:3000

Интегрированные API

  1. Погода: OpenWeatherMap API (требуется API ключ)
  2. Курсы валют: ExchangeRate-API

Дальнейшее развитие

  1. Доба_
Preview not available