-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (51 loc) · 1.92 KB
/
server.js
File metadata and controls
62 lines (51 loc) · 1.92 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
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const fetch = require('node-fetch');
const path = require('path');
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
// Enable CORS for the specific Render domain
const corsOptions = {
origin: ['https://electiq-votesaathi.onrender.com', 'http://localhost:3000'],
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));
app.use(express.json());
// Serve static files from the root directory
app.use(express.static(path.join(__dirname)));
/**
* GET /api/news
* Proxy endpoint for GNews API to resolve CORS issues
*/
app.get('/api/news', async (req, res) => {
try {
const apiKey = process.env.NEWS_API_KEY;
if (!apiKey) {
return res.status(500).json({ error: "Server Configuration Error: Missing NEWS_API_KEY" });
}
const query = encodeURIComponent("India elections");
const gnewsUrl = `https://gnews.io/api/v4/search?q=${query}&lang=en&country=in&max=10&token=${apiKey}`;
console.log("Proxying request to GNews API...");
const response = await fetch(gnewsUrl);
if (!response.ok) {
const errorText = await response.text();
console.error("GNews API Error:", errorText);
return res.status(response.status).json({ error: "Failed to fetch news from provider" });
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error("Proxy Server Error:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
// Fallback for SPA routing: serve index.html for all other routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(PORT, () => {
console.log(`ElectIQ Proxy Server running on port ${PORT}`);
console.log(`CORS enabled for: ${corsOptions.origin}`);
});