Show sourcecode
The following files exists in this folder. Click to view.
comments.php
exercises/
exercises.php
img/
incl/
index-no-include.php
index.php
server.js
source.php
style/
viewsource.php
server.js
54 lines UTF-8 Windows (CRLF)
// Kör: npm i express && node server.js
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
// (valfritt) servera statiska filer om du lägger CSS/JS i /public
app.use(express.static("public"));
app.get("/", (req, res) => {
// Senare: hämta från databas baserat på sökkriterier
const products = Array.from({ length: 20 }, (_, idx) => {
const id = idx + 1;
return { id, name: `car number ${id}`, price: 123 * id };
});
// Generera HTML ungefär som i PHP-exemplet
const productHtml = products
.map(
(p) => `
<div class="product">
<p>${p.name}</p>
<p>price ${p.price}$</p>
<button onclick="addToCart(${p.id});">Add ${p.id} to Cart</button>
</div>`
)
.join("\n");
res.type("html").send(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cart</title>
<style>
body { font-family: system-ui, Arial, sans-serif; }
.product { padding: 8px 12px; border: 1px solid #ddd; border-radius: 8px; margin: 8px 0; }
button { cursor: pointer; }
</style>
<script>
function addToCart(id) {
document.getElementById("msg").innerHTML += 'Car ' + id + ' added<br>';
// Senare: Lagra i databas via fetch('/api/cart', { method:'POST', body: JSON.stringify({ id }) })
}
</script>
</head>
<body>
<h1 id="msg">Cart:<br></h1>
${productHtml}
</body>
</html>`);
});
app.listen(PORT, () => {
console.log("Server listening on http://localhost:" + PORT);
});