-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
58 lines (49 loc) · 1.31 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
const express = require("express");
const app = express();
const path = require("path");
const dotenv = require("dotenv");
dotenv.config();
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
app.post("/shorten-url", async (req, res) => {
const inputUrl = req.body.url;
if (!isValidUrl(inputUrl)) {
return res.status(400).json({ error: "Invalid URL" });
}
const url = process.env.API_URL;
const options = {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
"X-RapidAPI-Key": process.env.API_KEY,
"X-RapidAPI-Host": process.env.API_HOST,
},
body: new URLSearchParams({
url: inputUrl,
}),
};
try {
const response = await fetch(url, options);
const result = await response.json();
const shortenedUrl = result.result_url;
res.json({ shortenedUrl });
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Something went wrong" });
}
});
const isValidUrl = (url) => {
try {
new URL(url);
return true;
} catch (error) {
return false;
}
};
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running at port ${port}`);
});