File size: 1,391 Bytes
0ed2558
 
 
 
 
 
2e409e2
 
 
 
 
 
 
 
 
 
 
 
0ed2558
2e409e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ed2558
 
2e409e2
0ed2558
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * API utility — all calls to the backend
 */
const API_BASE = '/api'

export async function submitContact(data) {
  let response
  try {
    response = await fetch(`${API_BASE}/contact`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
  } catch (networkErr) {
    throw new Error('Network error — please check your connection and try again.')
  }

  // Safely parse JSON — guard against Nginx returning HTML error pages
  let json = null
  const contentType = response.headers.get('content-type') || ''
  if (contentType.includes('application/json')) {
    try {
      json = await response.json()
    } catch {
      throw new Error('Server returned an unexpected response. Please try again.')
    }
  } else {
    // Non-JSON body (e.g. Nginx 502/504 HTML page)
    const text = await response.text().catch(() => '')
    console.error('[API] Non-JSON response from server:', response.status, text.slice(0, 200))
    throw new Error(
      response.status === 502 || response.status === 503
        ? 'The server is temporarily unavailable. Please try again in a moment.'
        : `Unexpected server response (${response.status}). Please try again.`
    )
  }

  if (!response.ok) {
    throw new Error((json && json.error) || 'Something went wrong. Please try again.')
  }

  return json
}