-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
71 lines (57 loc) · 1.77 KB
/
app.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
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const cors = require('cors');
// Initialize Express app
const app = express();
app.use(bodyParser.json());
app.use(cors()); // Enable CORS for frontend requests
// In-memory store for URLs
const urlDatabase = new Map();
// Helper function to create a random path
const generateShortId = () => crypto.randomBytes(8).toString('hex');
// Route to shorten URLs
app.post('/api/shorten', (req, res) => {
const { originalUrl } = req.body;
// Validate URL
try {
new URL(originalUrl); // Throws error if invalid
} catch (_) {
return res.status(400).json({ error: 'Invalid URL' });
}
// Generate a unique short ID
const shortId = generateShortId();
urlDatabase.set(shortId, originalUrl);
// Send the shortened URL
res.json({ shortUrl: `http://localhost:5000/${shortId}` });
});
// Route to redirect to the original URL
app.get('/:shortId', (req, res) => {
const { shortId } = req.params;
const originalUrl = urlDatabase.get(shortId);
if (originalUrl) {
res.redirect(originalUrl);
} else {
res.status(404).send('URL not found');
}
});
// Route to check if URL is detected by Facebook
app.get('/api/check-url/:shortId', (req, res) => {
const { shortId } = req.params;
const originalUrl = urlDatabase.get(shortId);
if (originalUrl) {
// Return some obfuscated response to avoid detection
res.json({ obfuscatedResponse: `You are being redirected to a URL` });
} else {
res.status(404).send('URL not found');
}
});
// hello world route
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});