-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
70 lines (61 loc) · 2.1 KB
/
server.js
File metadata and controls
70 lines (61 loc) · 2.1 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import express from 'express';
import path from 'path';
import fetch from 'node-fetch';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import dotenv from 'dotenv';
import cors from 'cors';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const PORT = process.env.PORT || 8081;
// Enable CORS
app.use(cors());
// Serve static files from the "public" directory
app.use(express.static(path.join(process.cwd(), 'public')));
// Proxy SWAPI people endpoint
app.get('/api/people', async (req, res) => {
console.log('Start app.get from SWAPI...');
try {
console.log('Trying to fetch people from SWAPI...');
let allPeople = [];
let nextUrl = 'https://swapi.py4e.com/api/people/';
console.log('Initial URL:', nextUrl);
while (nextUrl) {
console.log('Next URL:', nextUrl);
const response = await fetch(nextUrl);
if (!response.ok) throw new Error('Failed to fetch people');
console.log('Response received from SWAPI:', response.status);
const data = await response.json();
allPeople = [...allPeople, ...data.results];
nextUrl = data.next;
}
res.json(allPeople);
} catch (err) {
console.error('Error fetching people from SWAPI:', err);
res.status(500).json({ error: err.message });
}
});
// Proxy SWAPI planets endpoint with pagination
app.get('/api/planets', async (req, res) => {
const page = req.query.page || 1;
const swapiUrl = `https://swapi.py4e.com/api/planets/?page=${page}`;
try {
const response = await fetch(swapiUrl);
if (!response.ok) throw new Error('Failed to fetch planets');
const data = await response.json();
res.json(data);
} catch (err) {
console.error('Error fetching planets from SWAPI:', err);
res.status(500).json({ error: err.message });
}
});
// Catch-all route to serve the main HTML file
app.get('*', (req, res) => {
res.sendFile(path.join(process.cwd(), 'public', 'index.html'));
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});