-
Notifications
You must be signed in to change notification settings - Fork 0
/
serveraxios.js
99 lines (86 loc) · 2.57 KB
/
serveraxios.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const http = require('http'); // Nécessaire pour createServer
const axios = require('axios');
const Feed = require('./rss');
const PORT = process.env.PORT || 8888;
function getFeedUrl(request) {
const urlParams = new URL(request.url, 'http://localhost').searchParams;
return urlParams.get('url');
}
function writeError(err, response) {
console.log('Writing error response:', err);
response.writeHead(500, {
"Content-Type": "text/plain;charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type"
});
response.write(JSON.stringify({ error: err.message || err }) + "\n");
response.end();
}
function writeJsonResponse(rss, response) {
console.log('Writing JSON response');
response.writeHead(200, {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*"
});
response.write(JSON.stringify(rss, null, 2));
response.end();
}
async function followRedirects(feedUrl) {
try {
console.log('[DEBUG] Trying URL:', feedUrl);
const response = await axios.get(feedUrl, {
maxRedirects: 5,
validateStatus: status => status < 400
});
console.log('[DEBUG] Final URL:', response.request.res.responseUrl);
return response.request.res.responseUrl || feedUrl;
} catch (error) {
console.error('[DEBUG] Axios error:', error.message);
throw error;
}
}
function handleRequest(request, response) {
// Ignorer les requêtes favicon.ico
if (request.url === '/favicon.ico') {
response.writeHead(204);
response.end();
return;
}
if (request.method === 'OPTIONS') {
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type"
});
response.end();
return;
}
let feedUrl = getFeedUrl(request);
if (!feedUrl) {
writeError('No URL provided', response);
return;
}
console.log('Processing feed URL:', feedUrl);
if (!/^https?:\/\//i.test(feedUrl)) {
feedUrl = 'https://' + feedUrl;
}
followRedirects(feedUrl)
.then(finalUrl => {
console.log('Final URL after redirects:', finalUrl);
Feed.load(finalUrl, (err, rss) => {
if (err) {
writeError(err, response);
} else {
writeJsonResponse(rss, response);
}
});
})
.catch(err => {
writeError(err, response);
});
}
const server = http.createServer(handleRequest);
server.listen(PORT, () => {
console.log("Server started on port %s", PORT);
});