This commit is contained in:
54
webseite/backend/server.js
Normal file
54
webseite/backend/server.js
Normal file
@@ -0,0 +1,54 @@
|
||||
import express from 'express';
|
||||
import color from 'chalk';
|
||||
import cors from 'cors';
|
||||
|
||||
// Model
|
||||
import ProductModel from './model/ProductModel.js'; // Dateiendung nicht vergessen
|
||||
|
||||
const PORT = 8000;
|
||||
const HOST = '127.0.0.1'; // 'localhost'
|
||||
const BASE_URL = `http://${HOST}:${PORT}`;
|
||||
|
||||
const app = express();
|
||||
const products = ProductModel();
|
||||
|
||||
const corsOptions = {
|
||||
origin: 'http://localhost:3000',
|
||||
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
|
||||
};
|
||||
|
||||
// lade Produkte
|
||||
products.load();
|
||||
|
||||
// Middleware
|
||||
app.use(cors(corsOptions)); // Fängt alle HTTP-Requests vor den Routenabfragen ab.
|
||||
|
||||
// Routes
|
||||
app.get('/', (req, res) => {
|
||||
// console.log(req.headers);
|
||||
|
||||
res.send('SERVER WORKS!'); // HTTP-Response wird gesendet.
|
||||
});
|
||||
|
||||
app.get('/persons', (req, res) => {
|
||||
// res.setHeader('Content-Type', 'application/json'); // nicht notwendig den Content-Type selber zu definieren, da das express automatisch zuweist.
|
||||
|
||||
const persons = [
|
||||
{ firstName: 'John', lastName: 'Wick' },
|
||||
{ firstName: 'Jane', lastName: 'Doe' },
|
||||
{ firstName: 'Max', lastName: 'Mustermann' },
|
||||
];
|
||||
// res.send(JSON.stringify(persons)); // nicht notwendig JS Objekte in JSON Strings umzuwandeln, das das express automatisch umwandelt
|
||||
|
||||
res.send(persons);
|
||||
});
|
||||
|
||||
app.get('/api/products', (req, res) => {
|
||||
const data = products.getAll();
|
||||
res.send(data);
|
||||
});
|
||||
|
||||
app.listen(PORT, HOST, () => {
|
||||
console.log(color.magenta(`🚀 Server is running at: ${BASE_URL}`));
|
||||
console.log(color.yellow('CTRL + C to close.'));
|
||||
});
|
||||
Reference in New Issue
Block a user