Yaltopia-Ticket-Admin/dev-docs/TROUBLESHOOTING.md

485 lines
8.5 KiB
Markdown

# Troubleshooting Guide
## Common Issues and Solutions
### 1. ERR_CONNECTION_REFUSED
**Error:**
```
POST http://localhost:3000/api/v1/auth/login net::ERR_CONNECTION_REFUSED
```
**Cause:** Backend server is not running or running on a different port.
**Solutions:**
#### A. Start Your Backend Server
```bash
# Navigate to backend directory
cd path/to/backend
# Start the server
npm run dev
# or
npm start
# or
node server.js
# or
python manage.py runserver # Django
# or
php artisan serve # Laravel
```
#### B. Check Backend Port
1. Find which port your backend is running on
2. Update `.env` file:
```env
# If backend is on port 3001
VITE_API_URL=http://localhost:3001/api/v1
# If backend is on port 8000
VITE_API_URL=http://localhost:8000/api/v1
# If backend is on port 5000
VITE_API_URL=http://localhost:5000/api/v1
```
3. Restart your frontend:
```bash
# Stop the dev server (Ctrl+C)
# Start again
npm run dev
```
#### C. Verify Backend is Running
```bash
# Test if backend is accessible
curl http://localhost:3000/api/v1/auth/login
# Or open in browser
http://localhost:3000
```
#### D. Check for Port Conflicts
```bash
# Windows - Check what's using port 3000
netstat -ano | findstr :3000
# Kill process if needed (replace PID)
taskkill /PID <PID> /F
```
---
### 2. CORS Error
**Error:**
```
Access to XMLHttpRequest at 'http://localhost:3000/api/v1/auth/login'
from origin 'http://localhost:5173' has been blocked by CORS policy
```
**Cause:** Backend not configured to allow requests from frontend.
**Solution:** Configure CORS on backend
**Node.js/Express:**
```javascript
const cors = require('cors')
app.use(cors({
origin: 'http://localhost:5173', // Your frontend URL
credentials: true
}))
```
**Django:**
```python
# settings.py
CORS_ALLOWED_ORIGINS = [
"http://localhost:5173",
]
CORS_ALLOW_CREDENTIALS = True
```
**Laravel:**
```php
// config/cors.php
'allowed_origins' => ['http://localhost:5173'],
'supports_credentials' => true,
```
---
### 3. 404 Not Found
**Error:**
```
POST http://localhost:3000/api/v1/auth/login 404 (Not Found)
```
**Cause:** Backend endpoint doesn't exist or path is wrong.
**Solutions:**
#### A. Verify Backend Route
Check if your backend has the login route:
```javascript
// Should have something like:
app.post('/api/v1/auth/login', loginController)
```
#### B. Check API Path
Your backend might use a different path:
```env
# If backend uses /api/auth/login
VITE_API_URL=http://localhost:3000/api
# If backend uses /auth/login
VITE_API_URL=http://localhost:3000
# If backend uses /v1/auth/login
VITE_API_URL=http://localhost:3000/v1
```
#### C. Test Backend Directly
```bash
# Test with curl
curl -X POST http://localhost:3000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"test123"}'
```
---
### 4. 401 Unauthorized
**Error:**
```
POST http://localhost:3000/api/v1/auth/login 401 (Unauthorized)
```
**Cause:** Invalid credentials or backend authentication issue.
**Solutions:**
#### A. Check Credentials
- Verify email/password are correct
- Check if user exists in database
- Verify user is active
#### B. Check Backend Password Hashing
```javascript
// Backend should compare hashed passwords
const isValid = await bcrypt.compare(password, user.hashedPassword)
```
#### C. Check Database
```sql
-- Verify user exists
SELECT * FROM users WHERE email = 'admin@example.com';
-- Check if password is hashed
SELECT password FROM users WHERE email = 'admin@example.com';
```
---
### 5. 403 Forbidden
**Error:**
```
POST http://localhost:3000/api/v1/auth/login 403 (Forbidden)
```
**Cause:** User doesn't have admin role or account is inactive.
**Solutions:**
#### A. Check User Role
```sql
-- Update user role to ADMIN
UPDATE users SET role = 'ADMIN' WHERE email = 'admin@example.com';
```
#### B. Check Active Status
```sql
-- Activate user account
UPDATE users SET is_active = true WHERE email = 'admin@example.com';
```
#### C. Frontend Validation
The frontend checks `user.role === 'ADMIN'`. Make sure backend returns correct role.
---
### 6. Network Error (No Response)
**Error:**
```
Network Error
```
**Causes & Solutions:**
#### A. Backend Crashed
Check backend console for errors and restart.
#### B. Firewall Blocking
Temporarily disable firewall or add exception.
#### C. Wrong Protocol
```env
# Use http for local development
VITE_API_URL=http://localhost:3000/api/v1
# NOT https
# VITE_API_URL=https://localhost:3000/api/v1
```
---
### 7. Environment Variables Not Loading
**Error:**
API calls go to wrong URL or undefined.
**Solutions:**
#### A. Create .env File
```bash
# Copy example file
cp .env.example .env
# Edit with your values
VITE_API_URL=http://localhost:3000/api/v1
```
#### B. Restart Dev Server
```bash
# Stop server (Ctrl+C)
# Start again
npm run dev
```
#### C. Check Variable Name
Must start with `VITE_`:
```env
# ✅ Correct
VITE_API_URL=http://localhost:3000/api/v1
# ❌ Wrong (won't work)
API_URL=http://localhost:3000/api/v1
```
#### D. Access in Code
```typescript
// ✅ Correct
import.meta.env.VITE_API_URL
// ❌ Wrong
process.env.VITE_API_URL
```
---
### 8. Token Not Persisting
**Error:**
User logged out after page refresh.
**Solutions:**
#### A. Check localStorage
```javascript
// Open browser console
localStorage.getItem('access_token')
localStorage.getItem('user')
```
#### B. Check Cookie Settings
If using httpOnly cookies, check browser DevTools > Application > Cookies.
#### C. Backend Must Return Token
```json
{
"access_token": "...",
"user": { ... }
}
```
---
### 9. Infinite Redirect Loop
**Error:**
Page keeps redirecting between login and dashboard.
**Solutions:**
#### A. Check ProtectedRoute Logic
```typescript
// Should check for token
const token = localStorage.getItem('access_token')
if (!token) {
return <Navigate to="/login" />
}
```
#### B. Clear localStorage
```javascript
// Browser console
localStorage.clear()
// Then try logging in again
```
---
### 10. Tests Hanging
**Error:**
Tests run forever without completing.
**Solutions:**
#### A. Add Timeout
```typescript
// In test file
import { vi } from 'vitest'
vi.setConfig({ testTimeout: 10000 })
```
#### B. Mock Timers
```typescript
vi.useFakeTimers()
// ... test code
vi.useRealTimers()
```
#### C. Check for Unresolved Promises
Make sure all async operations complete.
---
## Debugging Tips
### 1. Check Browser Console
Press F12 and look for errors in Console tab.
### 2. Check Network Tab
1. Press F12
2. Go to Network tab
3. Try logging in
4. Click on the failed request
5. Check:
- Request URL
- Request Headers
- Request Payload
- Response
### 3. Check Backend Logs
Look at your backend console for error messages.
### 4. Test Backend Independently
Use curl or Postman to test backend without frontend.
### 5. Verify Environment Variables
```bash
# Check if .env file exists
ls -la .env
# Check contents
cat .env
```
### 6. Clear Browser Cache
Sometimes old cached files cause issues:
1. Press Ctrl+Shift+Delete
2. Clear cache and cookies
3. Restart browser
### 7. Check Node Version
```bash
node --version
# Should be 18.x or 20.x
```
---
## Quick Checklist
Before asking for help, verify:
- [ ] Backend server is running
- [ ] Backend is on correct port
- [ ] `.env` file exists with correct API URL
- [ ] Frontend dev server restarted after .env changes
- [ ] CORS configured on backend
- [ ] Login endpoint exists on backend
- [ ] Test user exists in database
- [ ] User has ADMIN role
- [ ] User account is active
- [ ] Browser console shows no errors
- [ ] Network tab shows request details
---
## Getting Help
If still stuck:
1. **Check Documentation**
- [Authentication Setup](./AUTHENTICATION.md)
- [Login API Documentation](./LOGIN_API_DOCUMENTATION.md)
- [API Standards](./API_STANDARDS.md)
2. **Gather Information**
- Error message
- Browser console logs
- Network tab details
- Backend logs
- Environment variables
3. **Test Systematically**
- Test backend with curl
- Test with Postman
- Check database directly
- Verify each step
---
## Common Development Setup
### Typical Setup
```
Frontend: http://localhost:5173 (Vite)
Backend: http://localhost:3000 (Node.js)
Database: localhost:5432 (PostgreSQL)
```
### .env Configuration
```env
VITE_API_URL=http://localhost:3000/api/v1
VITE_ENV=development
```
### Backend CORS
```javascript
app.use(cors({
origin: 'http://localhost:5173',
credentials: true
}))
```
### Test Login
```bash
curl -X POST http://localhost:3000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"admin@example.com","password":"admin123"}'
```
---
**Last Updated:** 2024