Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created January 20, 2026 00:00
Show Gist options
  • Select an option

  • Save prof3ssorSt3v3/f44a544ccec6b503fd5da8f6d13ef015 to your computer and use it in GitHub Desktop.

Select an option

Save prof3ssorSt3v3/f44a544ccec6b503fd5da8f6d13ef015 to your computer and use it in GitHub Desktop.
Steve's basic web server api
// import abc from './abc.js'; //local file import
// import express from 'express'; //node_modules
import http from 'node:http'; //import from NodeJS
const server = http.createServer(handleRequests);
const cheeses = ['Cheddar', 'Mozzarella', 'Danish Blue'];
function handleRequests(request, response) {
//every call from a client comes through here
switch (request.url) {
case '/api':
response.setHeader('Content-Type', 'text/plain');
response.writeHead(200);
response.end('API is working');
break;
case '/api/cheese':
// console.log(request.method);
if (request.method == 'GET') {
response.setHeader('Content-Type', 'application/json');
response.writeHead(200);
const data = {
cheeses: cheeses,
};
const str = JSON.stringify(data);
response.end(str);
} else if (request.method == 'POST') {
response.setHeader('Content-Type', 'application/json');
response.writeHead(201);
cheeses.push('Gouda');
console.log(cheeses);
response.end(JSON.stringify({ result: 'OK' }));
} else {
response.writeHead(405);
response.end('Method Not Allowed');
}
break;
case '/api/cheese/0':
response.setHeader('Content-Type', 'application/json');
response.writeHead(200);
response.end(JSON.stringify({ cheese: cheeses[0] }));
break;
case '/api/cheese/1':
response.setHeader('Content-Type', 'application/json');
response.writeHead(200);
response.end(JSON.stringify({ cheese: cheeses[1] }));
break;
case '/api/cheese/2':
response.setHeader('Content-Type', 'application/json');
response.writeHead(200);
response.end(JSON.stringify({ cheese: cheeses[2] }));
break;
default:
response.writeHead(200);
response.end(request.url);
}
}
const PORT = process.env.PORT ?? 3333;
// process.argv - arguments on the command line
// console.log(PORT);
server.listen(PORT, (err) => {
//callback function that runs on initial startup
if (err) {
return console.log(err);
//stops the code running
}
console.log(`Listening on PORT ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment