mnemo_cards/mnemo_cards_web_v2/TROUBLESHOOTING.md
2025-11-11 02:55:41 +03:00

291 lines
6.6 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 🔧 Устранение неполадок (Troubleshooting)
## 404 Error на `/packs/previews`
### Симптомы
```
GET http://localhost:8000/packs/previews 404 (Not Found)
```
### Причины и решения
#### 1⃣ Backend запущен старой версией
**Проверка:**
```bash
curl http://localhost:8000/packs/previews -H "app_version: 1.1.0"
# Если возвращает: {"detail":"Not Found"}
```
**Решение:**
```bash
cd mnemo_cards_backend
./restart_dev.sh
```
Или вручную:
```bash
# Остановить старый процесс
kill -9 $(lsof -ti:8000)
# Запустить заново
./run_dev.sh
```
#### 2⃣ Backend не запущен
**Проверка:**
```bash
lsof -ti:8000
# Если ничего не выводит - backend не запущен
```
**Решение:**
```bash
cd mnemo_cards_backend
./run_dev.sh
```
#### 3⃣ Неправильный порт в frontend
**Проверка:**
Откройте `mnemo_cards_web_v2/lib/domain/config/api_config.dart`:
```dart
static String get baseUrl => const String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'http://localhost:8000', // ← Должен быть 8000
);
```
**Решение:**
Если порт неправильный, исправьте и перезапустите Flutter:
```bash
# Ctrl+C чтобы остановить
flutter run -d chrome
```
#### 4⃣ Generated код устарел
**Проверка:**
Если вы изменяли `@Route` аннотации в backend
**Решение:**
```bash
cd mnemo_cards_backend
dart run build_runner build --delete-conflicting-outputs
./run_dev.sh
```
---
## CORS Error
### Симптомы
```
Access to XMLHttpRequest at 'http://localhost:8000/...' from origin '...'
has been blocked by CORS policy
```
**См. [CORS_FIX.md](CORS_FIX.md) для подробного решения**
**Быстрое решение:**
1. Убедитесь что backend запущен с новой версией (с CORS настройками)
2. Перезапустите backend: `./restart_dev.sh`
3. Очистите кэш браузера: Ctrl+Shift+Delete
4. Перезагрузите страницу: Ctrl+R
---
## Проблемы с авторизацией
### Симптомы
```
GET http://localhost:8000/pack/123 401 (Unauthorized)
```
### Причины
Некоторые endpoints требуют авторизации:
- `/pack/:id` - требует user_token
- `/packs/actions` - требует user_token
- `/user` - требует user_token
Endpoints БЕЗ авторизации:
-`/packs/previews` - доступен всем
-`/games` - доступен всем
-`/user/create` - для создания пользователя
### Решение
1. Пройдите авторизацию через Google Sign-In
2. Token должен автоматически сохраниться
3. Все последующие запросы будут включать token
**Проверка token:**
Откройте DevTools → Application → Local Storage → Shared Preferences
Должен быть ключ `auth_token`
---
## Backend не стартует
### Симптом 1: Port already in use
```
SocketException: Failed to create server socket (OS Error: Address already in use)
```
**Решение:**
```bash
# Найти и убить процесс на порту 8000
kill -9 $(lsof -ti:8000)
# Или использовать другой порт
dart run lib/main.dart -p 8001 --isar isar --workdir $(pwd)
```
### Симптом 2: Isar database locked
```
IsarError: Database is already open in another instance
```
**Решение:**
```bash
# Закрыть все процессы использующие Isar
pkill -f dart
# Удалить lock файл
rm -rf isar/*.lock
# Перезапустить
./run_dev.sh
```
### Симптом 3: Missing dependencies
```
Error: Could not resolve the package 'some_package'
```
**Решение:**
```bash
dart pub get
./run_dev.sh
```
---
## Flutter Web не запускается
### Симптом 1: Chrome not found
**Решение:**
```bash
# Укажите путь к Chrome
export CHROME_EXECUTABLE="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
flutter run -d chrome
```
### Симптом 2: Build failed
**Решение:**
```bash
flutter clean
flutter pub get
flutter run -d chrome
```
---
## Диагностические команды
### Проверить backend
```bash
# Запущен ли backend
lsof -ti:8000
# Доступен ли API
curl http://localhost:8000/games
# Проверить CORS
curl -X OPTIONS -H "Origin: http://localhost:8080" http://localhost:8000/games -v
```
### Проверить frontend config
```bash
# Показать текущий API URL
grep -A2 "baseUrl" mnemo_cards_web_v2/lib/domain/config/api_config.dart
```
### Логи backend
Backend выводит все запросы в консоль:
```
[app] GET /packs/previews
[app] POST /user/create
```
Смотрите терминал где запущен `./run_dev.sh`
### Логи frontend
Откройте DevTools (F12) → Console
Все HTTP ошибки будут показаны там
---
## Полезные скрипты
### Backend
```bash
cd mnemo_cards_backend
# Запуск
./run_dev.sh
# Перезапуск с регенерацией кода
./restart_dev.sh
# Тестирование API
./test_api.sh
```
### Frontend
```bash
cd mnemo_cards_web_v2
# Запуск
flutter run -d chrome
# Тесты
flutter test
# Анализ кода
flutter analyze
```
---
## Еще помогает?
1. ✅ Перезагрузите IDE (Cursor/VS Code)
2. ✅ Перезагрузите терминалы
3. ✅ Очистите кэш Flutter: `flutter clean`
4. ✅ Обновите зависимости: `flutter pub get`
5. ✅ Проверьте что используете правильную ветку git
6. ✅ Проверьте `.gitignore` - может файлы не закоммичены
---
## Дополнительные ресурсы
- [QUICK_START.md](QUICK_START.md) - Быстрый старт
- [DEV_SETUP.md](DEV_SETUP.md) - Инструкция по разработке
- [CORS_FIX.md](CORS_FIX.md) - Решение CORS проблем
- [API_INTEGRATION_TEMP.md](API_INTEGRATION_TEMP.md) - API документация
---
**Если ничего не помогло - создайте issue с:**
1. Версия Flutter (`flutter --version`)
2. Версия Dart (`dart --version`)
3. OS версия
4. Полный текст ошибки
5. Логи backend и frontend