Zum Inhalt

GET und POST Handler

API Endpunkte

Methode Route Beschreibung
GET /cars Alle Autos zurückgeben
POST /cars Neues Auto hinzufügen

Code

cars.json

{
  "cars": {
    "sport": {
      "c1": {
        "question": "Welches Auto hat den stärksten Serienmotor?",
        "options": ["Ferrari 812", "Lamborghini Aventador", "Bugatti Chiron", "McLaren P1"],
        "answer": "Bugatti Chiron"
      }
    },
    "brands": {
      "c1": {
        "question": "Aus welchem Land kommt BMW?",
        "options": ["Italien", "Frankreich", "Deutschland", "Japan"],
        "answer": "Deutschland"
      },
      "c2": {
        "question": "Was bedeutet das Logo von Audi?",
        "options": ["4 Gründer", "4 Fusionen", "4 Modelle", "4 Länder"],
        "answer": "4 Fusionen"
      }
    }
  }
}

server.js

const express = require("express");
const fs = require("fs");
const app = express();
const port = 4008;

app.use(express.json());

let carsData = JSON.parse(fs.readFileSync("./cars.json", "utf-8"));

app.get("/cars", (req, res) => {
  res.json({ status: "success", data: carsData });
});

app.post("/cars", (req, res) => {
  const { category, id, question, options, answer } = req.body;

  if (!category || !id || !question || !options || !answer) {
    return res.status(400).json({
      error: "Felder: category, id, question, options, answer sind nötig.",
    });
  }

  if (!carsData.cars[category]) {
    carsData.cars[category] = {};
  }

  carsData.cars[category][id] = { question, options, answer };

  res.status(201).json({
    message: "Auto hinzugefügt!",
    added: { question, options, answer },
  });
});

app.listen(port, () => {
  console.log(`Server läuft auf http://localhost:${port}`);
});

Deployment auf Raspberry Pi

Server: 10.27.160.12
Port: 4008
Pfad: /home/m295/class/lars

scp -r server.js cars.json m295@10.27.160.12:/home/m295/class/lars/
ssh m295@10.27.160.12
cd /home/m295/class/lars
npm install
node server.js

Testen mit Postman

GET /cars

Request:

GET http://10.27.160.12:4008/cars

Response (200):

{
  "status": "success",
  "data": {
    "cars": {
      "sport": { "c1": { "question": "Welches Auto hat den stärksten Serienmotor?", "..." } },
      "brands": { "..." }
    }
  }
}

POST /cars

Request Body (JSON):

{
  "category": "brands",
  "id": "c3",
  "question": "Wann wurde Porsche gegründet?",
  "options": ["1931", "1945", "1963", "1972"],
  "answer": "1931"
}

Response (201):

{
  "message": "Auto hinzugefügt!",
  "added": {
    "question": "Wann wurde Porsche gegründet?",
    "options": ["1931", "1945", "1963", "1972"],
    "answer": "1931"
  }
}

Fehler (400):

{
  "error": "Felder: category, id, question, options, answer sind nötig."
}