-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.cjs
36 lines (30 loc) · 952 Bytes
/
server.cjs
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
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3001;
let fetch;
// Import node-fetch dynamically
import('node-fetch').then(module => {
fetch = module.default;
});
app.use(cors());
app.use(express.json());
app.get('/api/websitecarbon', async (req, res) => {
if (!fetch) {
return res.status(500).json({ error: 'Server initialization in progress' });
}
const apiUrl = 'https://api.websitecarbon.com/site?url=';
const siteEndpoint = req.query.url;
const fullUrl = `${apiUrl}${siteEndpoint}`;
try {
const response = await fetch(fullUrl);
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Error fetching data:', error);
res.status(500).json({ error: 'Failed to fetch data' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});