|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * API Connection Test Script |
| 5 | + * Tests backend connectivity and CORS configuration before starting the frontend |
| 6 | + */ |
| 7 | + |
| 8 | +// Use built-in fetch for Node.js 18+ or fallback to node-fetch |
| 9 | +let fetch; |
| 10 | +try { |
| 11 | + // Try to use built-in fetch (Node.js 18+) |
| 12 | + fetch = globalThis.fetch; |
| 13 | + if (!fetch) { |
| 14 | + throw new Error('Built-in fetch not available'); |
| 15 | + } |
| 16 | +} catch (e) { |
| 17 | + // Fallback to node-fetch for older Node.js versions |
| 18 | + const { default: nodeFetch } = await import('node-fetch'); |
| 19 | + fetch = nodeFetch; |
| 20 | +} |
| 21 | + |
| 22 | +const API_BASE_URL = process.env.REACT_APP_API_URL || 'https://eproject3.onrender.com/api'; |
| 23 | + |
| 24 | +const tests = [ |
| 25 | + { |
| 26 | + name: 'Health Check', |
| 27 | + url: `${API_BASE_URL.replace('/api', '')}/health`, |
| 28 | + method: 'GET', |
| 29 | + expectStatus: 200, |
| 30 | + }, |
| 31 | + { |
| 32 | + name: 'Vehicle Models (Anonymous)', |
| 33 | + url: `${API_BASE_URL}/VehicleModels?pageNumber=1&pageSize=5`, |
| 34 | + method: 'GET', |
| 35 | + expectStatus: 200, |
| 36 | + checkCors: true, |
| 37 | + }, |
| 38 | + { |
| 39 | + name: 'Auth Login Endpoint', |
| 40 | + url: `${API_BASE_URL}/auth/login`, |
| 41 | + method: 'POST', |
| 42 | + expectStatus: 400, // Should return 400 for missing body, not 404 |
| 43 | + body: {}, |
| 44 | + }, |
| 45 | +]; |
| 46 | + |
| 47 | +async function testEndpoint(test) { |
| 48 | + console.log(`\n🧪 Testing: ${test.name}`); |
| 49 | + console.log(` URL: ${test.url}`); |
| 50 | + console.log(` Method: ${test.method}`); |
| 51 | + |
| 52 | + try { |
| 53 | + const options = { |
| 54 | + method: test.method, |
| 55 | + headers: { |
| 56 | + 'Content-Type': 'application/json', |
| 57 | + 'Origin': 'http://localhost:3000', // Simulate frontend origin |
| 58 | + }, |
| 59 | + }; |
| 60 | + |
| 61 | + if (test.body) { |
| 62 | + options.body = JSON.stringify(test.body); |
| 63 | + } |
| 64 | + |
| 65 | + const response = await fetch(test.url, options); |
| 66 | + |
| 67 | + console.log(` Status: ${response.status} ${response.statusText}`); |
| 68 | + |
| 69 | + // Check CORS headers |
| 70 | + if (test.checkCors) { |
| 71 | + const corsOrigin = response.headers.get('Access-Control-Allow-Origin'); |
| 72 | + const corsMethods = response.headers.get('Access-Control-Allow-Methods'); |
| 73 | + const corsHeaders = response.headers.get('Access-Control-Allow-Headers'); |
| 74 | + |
| 75 | + console.log(` CORS Origin: ${corsOrigin || 'NOT SET'}`); |
| 76 | + console.log(` CORS Methods: ${corsMethods || 'NOT SET'}`); |
| 77 | + console.log(` CORS Headers: ${corsHeaders || 'NOT SET'}`); |
| 78 | + |
| 79 | + if (!corsOrigin) { |
| 80 | + console.log(' ❌ CORS not configured - requests from localhost will fail'); |
| 81 | + return false; |
| 82 | + } else { |
| 83 | + console.log(' ✅ CORS configured'); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + // Check response status |
| 88 | + if (response.status === test.expectStatus) { |
| 89 | + console.log(` ✅ Status matches expected (${test.expectStatus})`); |
| 90 | + } else { |
| 91 | + console.log(` ⚠️ Status ${response.status} differs from expected ${test.expectStatus}`); |
| 92 | + } |
| 93 | + |
| 94 | + // Try to parse response body for additional info |
| 95 | + try { |
| 96 | + const data = await response.text(); |
| 97 | + if (data) { |
| 98 | + console.log(` Response preview: ${data.substring(0, 100)}${data.length > 100 ? '...' : ''}`); |
| 99 | + } |
| 100 | + } catch (e) { |
| 101 | + // Ignore parsing errors |
| 102 | + } |
| 103 | + |
| 104 | + return true; |
| 105 | + |
| 106 | + } catch (error) { |
| 107 | + console.log(` ❌ Network Error: ${error.message}`); |
| 108 | + |
| 109 | + if (error.code === 'ENOTFOUND') { |
| 110 | + console.log(' 💡 Check if the backend URL is correct and accessible'); |
| 111 | + } else if (error.code === 'ECONNREFUSED') { |
| 112 | + console.log(' 💡 Backend server might be down or not accessible'); |
| 113 | + } |
| 114 | + |
| 115 | + return false; |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +async function runTests() { |
| 120 | + console.log('🚀 Starting API Connection Tests'); |
| 121 | + console.log(`📡 API Base URL: ${API_BASE_URL}`); |
| 122 | + console.log('=' .repeat(60)); |
| 123 | + |
| 124 | + let passedTests = 0; |
| 125 | + let totalTests = tests.length; |
| 126 | + |
| 127 | + for (const test of tests) { |
| 128 | + const passed = await testEndpoint(test); |
| 129 | + if (passed) passedTests++; |
| 130 | + |
| 131 | + // Small delay between tests |
| 132 | + await new Promise(resolve => setTimeout(resolve, 500)); |
| 133 | + } |
| 134 | + |
| 135 | + console.log('\n' + '=' .repeat(60)); |
| 136 | + console.log(`📊 Test Results: ${passedTests}/${totalTests} tests passed`); |
| 137 | + |
| 138 | + if (passedTests === totalTests) { |
| 139 | + console.log('✅ All tests passed! Backend is ready for frontend connection.'); |
| 140 | + process.exit(0); |
| 141 | + } else { |
| 142 | + console.log('❌ Some tests failed. Check backend configuration and connectivity.'); |
| 143 | + console.log('\n💡 Common issues:'); |
| 144 | + console.log(' - Backend server not running'); |
| 145 | + console.log(' - CORS not configured for localhost:3000'); |
| 146 | + console.log(' - Wrong API URL in environment variables'); |
| 147 | + console.log(' - Network connectivity issues'); |
| 148 | + process.exit(1); |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +// Handle unhandled promise rejections |
| 153 | +process.on('unhandledRejection', (reason, promise) => { |
| 154 | + console.error('Unhandled Rejection at:', promise, 'reason:', reason); |
| 155 | + process.exit(1); |
| 156 | +}); |
| 157 | + |
| 158 | +runTests().catch(error => { |
| 159 | + console.error('Test runner failed:', error); |
| 160 | + process.exit(1); |
| 161 | +}); |
0 commit comments