projPara/server.js
2024-06-13 22:37:36 +02:00

66 lines
1.9 KiB
JavaScript

const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const app = express();
const port = 3000;
// Ustawienia bodyParser do obsługi danych w formacie JSON
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Połączenie z bazą danych SQLite
const db = new sqlite3.Database('tasks.db');
// tworzenie tabeli tasks, jeśli jeszcze nie istnieje
db.serialize(() => {
db.run("CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, task TEXT)");
});
// Obsługa CORS, czyli ograniczenie żądań stron internetowych z innej domeny
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
next();
});
// Dodawanie zadania
app.post('/addTask', (req, res) => {
const task = req.body.task;
if (task) {
db.run("INSERT INTO tasks (task) VALUES (?)", task, function(err) {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ id: this.lastID, task: task });
});
} else {
res.status(400).json({ error: "No task provided" });
}
});
// Usuwanie zadania
app.delete('/deleteTask/:id', (req, res) => {
const id = req.params.id;
db.run("DELETE FROM tasks WHERE id = ?", id, function(err) {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ success: true });
});
});
// Pobieranie wszystkich zadań
app.get('/tasks', (req, res) => {
db.all("SELECT * FROM tasks", [], (err, rows) => {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json(rows);
});
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});