Home
- Details
- Written by: d4brain
- Category: Uncategorised
- Hits: 42
Dieses Beispiel verbindet einen kleinen Node.js-Server mit mehreren Browser-Clients. Nachrichten erscheinen ohne Neuladen bei allen verbundenen Teilnehmern.
Projektstruktur
vibe-chat/
package.json
server.js
public/index.html
package.json
{
"scripts":{"start":"node server.js"},
"dependencies":{"ws":"^8.18.0"}
}
Server: server.js
const http=require('node:http');
const fs=require('node:fs');
const path=require('node:path');
const {WebSocketServer}=require('ws');
const server=http.createServer(function(req,res){
fs.readFile(path.join(__dirname,'public','index.html'),function(error,data){
if(error){res.writeHead(500);return res.end('Fehler')}
res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(data);
});
});
const wss=new WebSocketServer({server});
wss.on('connection',function(socket){
socket.on('message',function(raw){
const message=raw.toString().slice(0,500);
wss.clients.forEach(function(client){if(client.readyState===1)client.send(message)});
});
});
server.listen(3000,function(){console.log('Chat: http://localhost:3000')});
Client: public/index.html
<!doctype html><html lang="de"><meta charset="utf-8"><title>Vibe Chat</title>
<h1>Vibe Chat</h1><ul id="messages"></ul>
<form id="form"><input id="text" required maxlength="500" autocomplete="off"><button>Senden</button></form>
<script>
const socket=new WebSocket('ws://'+location.host);
socket.onmessage=function(event){
const li=document.createElement('li');li.textContent=event.data;document.querySelector('#messages').append(li);
};
document.querySelector('#form').onsubmit=function(event){
event.preventDefault();const input=document.querySelector('#text');
if(socket.readyState===WebSocket.OPEN){socket.send(input.value);input.value=''}
};
</script></html>
Ausführen
npm install
npm start
Öffne http://localhost:3000 in zwei Browserfenstern und sende Nachrichten in beide Richtungen.
Sinnvolle Folgeprompts
- Nutzernamen und Zeitstempel
- Getrennte Chat-Räume
- Reconnect-Anzeige und Rate-Limit
- Details
- Written by: d4brain
- Category: Uncategorised
- Hits: 38
Hier entsteht eine kleine JSON-API ausschließlich mit Node.js-Bordmitteln. Das macht Request-Routing, Statuscodes und Datenfluss transparent.
Startprompt
Erstelle mit dem eingebauten http-Modul eine REST-API für Notizen. Implementiere GET /api/notes und POST /api/notes, JSON-Parsing, Fehlerbehandlung und CORS für einen lokalen Client.
Datei: server.js
const http=require('node:http');
const notes=[{id:1,text:'Erstes Vibe-Coding-Beispiel'}];
function send(res,status,data){
res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Access-Control-Allow-Origin':'*'});
res.end(JSON.stringify(data));
}
const server=http.createServer(function(req,res){
if(req.method==='GET' && req.url==='/api/notes')return send(res,200,notes);
if(req.method==='POST' && req.url==='/api/notes'){
let body='';
req.on('data',function(chunk){body+=chunk;if(body.length>1e6)req.destroy()});
req.on('end',function(){
try{
const input=JSON.parse(body);
if(typeof input.text!=='string'||!input.text.trim())return send(res,400,{error:'text ist erforderlich'});
const note={id:Date.now(),text:input.text.trim()};notes.push(note);send(res,201,note);
}catch(error){send(res,400,{error:'Ungültiges JSON'})}
});
return;
}
send(res,404,{error:'Nicht gefunden'});
});
server.listen(3000,function(){console.log('API: http://localhost:3000/api/notes')});
Starten und testen
node server.js
curl http://localhost:3000/api/notes
curl -X POST http://localhost:3000/api/notes -H "Content-Type: application/json" -d "{"text":"API testen"}"
Prüfliste
- GET liefert Status 200 und ein Array.
- POST liefert Status 201.
- Leerer Text und kaputtes JSON liefern Status 400.
- Unbekannte Routen liefern Status 404.
Nächste Schritte
- DELETE-Route ergänzen
- Daten in einer Datei oder SQLite speichern
- Tests mit dem eingebauten Node-Test-Runner schreiben
- Details
- Written by: d4brain
- Category: Uncategorised
- Hits: 36
Dieses Beispiel zeigt eine typische kleine Web-App: Eingaben werden geprüft, als strukturierte Daten angezeigt und als JSON-Datei exportiert.
Ziel
Ein Projektformular erfasst Name, Sprache und Beschreibung. JavaScript nutzt die native Browser-Validierung und erzeugt anschließend eine herunterladbare JSON-Datei.
Startprompt
Erstelle ein barrierearmes HTML-Formular für Projektdaten. Validiere Pflichtfelder, zeige das Ergebnis als formatiertes JSON und biete einen Download ohne Backend an.
Vollständige Datei: index.html
<!doctype html><html lang="de"><meta charset="utf-8">
<title>Projekt-Generator</title>
<style>body{font:16px system-ui;max-width:720px;margin:2rem auto}label{display:block;margin:1rem 0}input,select,textarea{display:block;width:100%;padding:.6rem}pre{background:#111827;color:#d1fae5;padding:1rem;white-space:pre-wrap}</style>
<h1>Projekt-Generator</h1>
<form id="project">
<label>Name<input name="name" required minlength="3"></label>
<label>Sprache<select name="language"><option>JavaScript</option><option>Node.js</option><option>C++</option></select></label>
<label>Beschreibung<textarea name="description" required maxlength="240"></textarea></label>
<button>JSON erzeugen</button> <button type="button" id="download" disabled>Download</button>
</form><pre id="output">Noch keine Daten.</pre>
<script>
let current=null;
document.querySelector('#project').onsubmit=function(event){
event.preventDefault();
if(!this.reportValidity())return;
current=Object.fromEntries(new FormData(this));
document.querySelector('#output').textContent=JSON.stringify(current,null,2);
document.querySelector('#download').disabled=false;
};
document.querySelector('#download').onclick=function(){
const blob=new Blob([JSON.stringify(current,null,2)],{type:'application/json'});
const link=document.createElement('a');
link.href=URL.createObjectURL(blob);link.download='projekt.json';link.click();
URL.revokeObjectURL(link.href);
};
</script></html>
Prüfen
- Leere Pflichtfelder absenden.
- Gültige Projektdaten eingeben.
- JSON herunterladen und in einem Editor öffnen.
Folgeprompts
- Import einer vorhandenen JSON-Datei
- Mehrere Projekte als Liste verwalten
- Schema-Version und Erstellungsdatum ergänzen
- Details
- Written by: d4brain
- Category: Uncategorised
- Hits: 36
In diesem Beispiel entsteht ein kleines Reaktionsspiel mit Canvas, Game Loop und Punktestand. Es benötigt keine Bibliothek und ist ideal für schnelle Iterationen.
Spielidee
Klicke innerhalb von 30 Sekunden möglichst oft auf den wandernden Kreis. Jeder Treffer erhöht den Punktestand.
Startprompt
Baue ein Browser-Spiel in einer HTML-Datei. Zeichne mit Canvas einen zufällig springenden Zielkreis, zähle Treffer und zeige eine 30-Sekunden-Uhr. Unterstütze Maus und Touch.
Vollständige Datei: index.html
<!doctype html><html lang="de"><meta charset="utf-8">
<title>Catch the Dot</title>
<style>body{font:18px system-ui;text-align:center;background:#101522;color:#fff}canvas{max-width:92vw;background:#18243a;border:2px solid #62e6ff;border-radius:12px;touch-action:none}</style>
<h1>Catch the Dot</h1><p>Punkte: <b id="score">0</b> · Zeit: <b id="time">30</b>s</p>
<canvas id="game" width="640" height="360"></canvas>
<script>
const canvas=document.querySelector('#game'),ctx=canvas.getContext('2d');
let x=160,y=120,r=24,score=0,left=30,running=true;
function move(){x=r+Math.random()*(canvas.width-r*2);y=r+Math.random()*(canvas.height-r*2)}
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle=running?'#ffce3a':'#64748b';
ctx.beginPath();ctx.arc(x,y,r,0,Math.PI*2);ctx.fill();
requestAnimationFrame(draw);
}
function hit(event){
if(!running)return;
const box=canvas.getBoundingClientRect();
const px=(event.clientX-box.left)*canvas.width/box.width;
const py=(event.clientY-box.top)*canvas.height/box.height;
if(Math.hypot(px-x,py-y)<=r){score++;document.querySelector('#score').textContent=score;move()}
}
canvas.addEventListener('pointerdown',hit);
const timer=setInterval(function(){
left--;document.querySelector('#time').textContent=left;
if(left<=0){running=false;clearInterval(timer)}
},1000);
move();draw();
</script></html>
Testen
Öffne die Datei, prüfe Maus und Touch und kontrolliere, dass nach 30 Sekunden keine Treffer mehr gezählt werden.
Nächste Iterationen
- Schwierigkeitsstufen und kleinere Ziele
- Highscore in localStorage
- Partikeleffekt und Sound bei Treffern