trxshortlink/server/index.js

36 lines
1.1 KiB
JavaScript

const express = require("express");
const cors = require("cors");
const sqlite3 = require("sqlite3").verbose();
const app = express();
require("dotenv").config();
app.use(cors());
app.use(express.json());
const db = new sqlite3.Database("../db.sqlite");
// Beispiel-Route: Link erstellen
app.post("/api/shorten", (req, res) => {
const { original_url } = req.body;
const id = Math.random().toString(36).substring(2, 8);
db.run(
"INSERT INTO links (id, original_url, created_at) VALUES (?, ?, datetime('now'))",
[id, original_url],
(err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ short_url: `http://localhost:3000/${id}` });
res.json({ id: `${id}`});
}
);
});
// Beispiel-Redirect
app.get("/:id", (req, res) => {
const id = req.params.id;
db.get("SELECT original_url FROM links WHERE id = ?", [id], (err, row) => {
if (row) res.redirect(row.original_url);
else res.status(404).send("Not found");
});
});
app.listen(3000, () => console.log("Server läuft auf http://localhost:3000"));