-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathserver.js
More file actions
63 lines (53 loc) · 1.67 KB
/
server.js
File metadata and controls
63 lines (53 loc) · 1.67 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
import express from 'express';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
import cors from 'cors';
dotenv.config();
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
// mock api route
app.get('/posts', async (req, res) => {
console.log("JSON Placeholder request triggered");
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch posts' });
}
});
// Public api route unnauthenticated
app.get('/weather', async (req, res) => {
console.log("Open weather map api request triggered");
const city = req.query.city || 'Chicago';
const apiKey = process.env.OPENWEATHER_API_KEY;
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
);
const data = await response.json();
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch weather data' });
}
});
// github api route
app.get('/repos', async (req, res) => {
console.log("GitHub request triggered");
const token = process.env.GITHUB_TOKEN;
console.log('GitHub Token:', process.env.GITHUB_TOKEN);
try {
const response = await fetch('https://api.github.com/user/repos', {
headers: {
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch GitHub repos' });
}
});
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));