Quando le richieste non vanno a buon fine, un debugging sistematico aiuta a identificare rapidamente il problema.
Abilita la registrazione dettagliata
async function debugRequest(url, options) {
console.log('=== API Request ===");
console.log('URL:', url);
console.log('Method:', options.method);
console.log('Headers:', {
...options.headers,
'x-api-key': options.headers['x-api-key']?.substring(0, 10) + '...'
});
console.log('Body:', options.body);
const startTime = Date.now();
try {
const response = await fetch(url, options);
const duration = Date.now() - startTime;
console.log('=== API Response ===");
console.log('Status:', response.status, response.statusText);
console.log('Duration:', duration + 'ms');
console.log('Headers:', Object.fromEntries(response.headers));
const data = await response.json();
console.log('Body:', data);
return { response, data };
} catch (error) {
console.error('=== Request Failed ===");
console.error('Error:', error.message);
console.error('Duration:', Date.now() - startTime + 'ms');
throw error;
}
}
Controlla prima queste cose
1. La chiave API è corretta:
console.log('API key starts with:', apiKey.substring(0, 10));
console.log('API key length:', apiKey.length);
2. Il nome dell’header è esatto:
// Deve essere in minuscolo 'x-api-key'
headers: {
'x-api-key': apiKey, // ✓ Corretto
'X-API-Key': apiKey, // ✗ Errato
'api-key': apiKey, // ✗ Errato
}
3. Il JSON è valido:
try {
const body = JSON.stringify({ query: 'test' });
console.log('Valid JSON:', body);
} catch (e) {
console.error('Invalid JSON:', e);
}
4. La richiesta raggiunge il server:
// Usa la scheda Network delle DevTools del browser oppure
curl -v -X POST https://api.cathopic.com/resources \
-H "x-api-key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"query": "test"}'
Errori comuni
Content-Type errato:
// ✗ Errato
headers: {
'Content-Type': 'text/plain'
}
// ✓ Corretto
headers: {
'Content-Type': 'application/json'
}
Non serializzare (stringify) il body:
// ✗ Errato
body: { query: 'test' }
// ✓ Corretto
body: JSON.stringify({ query: 'test' })
Usare GET invece di POST:
// ✗ Tutti gli endpoint richiedono POST
method: 'GET'
// ✓ Corretto
method: 'POST'
Testa con una richiesta minima
Riduci al minimo per isolare il problema:
const response = await fetch('https://api.cathopic.com/resources', {
method: 'POST',
headers: {
'x-api-key': 'YOUR_ACTUAL_KEY_HERE',
'Content-Type': 'application/json'
},
body: '{}' // Oggetto vuoto
});
console.log(response.status);
console.log(await response.json());
Se funziona, aggiungi gradualmente i parametri finché non si verifica l’errore.
Confronta con un esempio funzionante
Testa con curl per verificare la tua implementazione:
curl -X POST https://api.cathopic.com/resources \
-H "x-api-key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"query": "Jesus", "page": 1, "page_size": 5}'
Se curl funziona ma il tuo codice no, confronta gli header e il body esatti.
Se sei ancora bloccato?
Contatta l’assistenza per sviluppatori con:
Messaggio di errore completo
Header della richiesta (nascondi la tua chiave API completa)
Body della richiesta
Stato della risposta e body
Linguaggio di programmazione e libreria HTTP
Snippet di codice (senza esporre le credenziali)