3.1 KiB
3.1 KiB
🚀 Quick Deploy CORS Middleware
⚡ Langkah Cepat (Production Server)
# 1. Masuk ke folder project
cd /www/wwwroot/api.btekno.cloud/api
# 2. Pull code terbaru (yang sudah include CORS middleware)
git pull origin main
# 3. Regenerate autoloader (untuk load class CorsMiddleware)
composer dump-autoload --optimize
# 4. Edit .env dan tambahkan konfigurasi CORS
nano .env
Tambahkan ke file .env:
# CORS Configuration
CORS_ALLOWED_ORIGINS=*
CORS_ALLOWED_METHODS=GET,POST,PUT,DELETE,OPTIONS
CORS_ALLOWED_HEADERS=Content-Type,Authorization,X-API-KEY,Accept,Origin
CORS_ALLOW_CREDENTIALS=true
Untuk Production (lebih aman):
# Ganti * dengan domain yang diizinkan
CORS_ALLOWED_ORIGINS=https://app.example.com,https://dashboard.example.com
# 5. Restart PHP-FPM (via aaPanel atau command)
# Via aaPanel: Website -> PHP -> Service Management -> Reload
# Atau:
systemctl reload php-fpm-83 # Sesuaikan dengan PHP version
✅ Verifikasi CORS Aktif
Test 1: Cek Response Headers
curl -I -H "Origin: http://localhost:3000" https://api.btekno.cloud/health
Harus ada header:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-API-KEY, Accept, Origin
Test 2: Test Preflight (OPTIONS)
curl -X OPTIONS \
-H "Origin: http://localhost:3000" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: Content-Type,Authorization" \
https://api.btekno.cloud/auth/v1/login
Harus return: HTTP 204 No Content dengan CORS headers.
Test 3: Test dari Browser Console
Buka browser console (F12) dan jalankan:
fetch('https://api.btekno.cloud/health', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => {
console.log('✅ CORS OK:', data);
})
.catch(err => {
console.error('❌ CORS Error:', err);
});
🔍 Troubleshooting
Masalah: CORS headers tidak muncul
Solusi:
- Pastikan
CorsMiddlewaresudah di-load disrc/Bootstrap/app.php✅ - Pastikan
.envsudah ada konfigurasi CORS ✅ - Restart PHP-FPM ✅
- Clear browser cache dan coba lagi
Masalah: Preflight OPTIONS return 404
Solusi:
- Pastikan routing middleware sudah di-load setelah CORS middleware ✅
- Cek nginx config: pastikan
try_filesmengarah keindex.php
Masalah: CORS hanya work untuk localhost
Solusi:
- Edit
.envdan setCORS_ALLOWED_ORIGINSdengan domain yang benar - Atau gunakan
*untuk development (tidak recommended untuk production)
📝 Catatan Penting
-
CORS middleware sudah otomatis handle:
- Preflight OPTIONS request
- CORS headers di semua response
- Localhost detection (http://localhost, http://127.0.0.1 dengan port apapun)
-
Tidak perlu konfigurasi nginx untuk CORS - semua di-handle di PHP middleware
-
Untuk production: Ganti
CORS_ALLOWED_ORIGINS=*dengan list domain yang spesifik -
CORS headers akan muncul di semua endpoint - termasuk
/health,/auth,/retribusi, dll