-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
83 lines (79 loc) · 2.51 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
72
73
74
75
76
77
78
79
80
81
82
83
// Import necessary modules
const app = require('express')();
const mysql = require('mysql2');
// Create a new Express app
require('dotenv').config();
const PORT = process.env.PUBLIC_PORT || 3000;
// Create a connection pool
const pool = mysql.createPool({
host: process.env.SQL_HOST,
user: process.env.SQL_USER,
password: process.env.SQL_PASSWORD,
database: 'url_shortener'
});
if (process.env.PRODUCTION) {
app.get('/urls', (_req, res) => {
// Query the MySQL database for the urls table
pool.query('SELECT * FROM urls', (err, results) => {
if (err) {
console.error(err);
res.status(500).send('Error getting URL data!');
return;
}
res.json(results);
});
});
}
// Create a route to generate a short URL
app.get('/shorten', (req, res) => {
// Generate a short ID
const shortUrl = Math.random().toString(36).substring(2,7);
console.log(shortUrl);
// Get the long URL from the request
const longUrl = req.query.longUrl;
// Insert the short and long URLs into the MySQL database
pool.query(
`INSERT INTO urls (short_url, long_url, created_at) VALUES (?, ?, NOW())`,
[shortUrl, longUrl],
(err) => {
if (err) {
console.error(err);
res.status(500).send('Error generating short URL');
} else {
res.setHeader('Content-Type', 'text/plain'); //specify content type to prevent XSS
res.send(`http://${req.headers.host}${PORT === 80 ? '' : `${PORT}`}/${shortUrl}`);
}
}
);
});
// Create a route to redirect short URLs to their corresponding long URLs
app.get('/:shortUrl', (req, res) => {
// Get the short URL from the request
const shortUrl = req.params.shortUrl;
// Query the MySQL database for the corresponding long URL
pool.query(
`SELECT long_url FROM urls WHERE short_url = ?`,
[shortUrl],
(err, results) => {
if (err) {
console.error(err);
res.status(500).send('Error redirecting to long URL');
} else if (results.length === 0) {
res.status(404).send('Short URL not found');
} else {
// check if the long_url property exists
if (results[0].long_url) {
// Redirect the user to the long URL
res.redirect(results[0].long_url);
} else {
console.error('long_url property not found in results');
res.status(500).send('Error redirecting to long URL');
}
}
}
);
});
// Start the Express app on port 3000
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});