diff --git a/server/app.js b/server/app.js index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..40115d1a6857b04bf5afd75cb542e7c97141e8d4 100644 --- a/server/app.js +++ b/server/app.js @@ -0,0 +1,52 @@ +const http = require("http"); +const fs = require("fs"); +const hostname = "127.0.0.1"; +const port = 3000; +const serverUrl = `http://${hostname}:${port}`; + +const server = http.createServer((req, res) => { + console.log("A new incoming HTTP request has been received with method type: " + req.method); + const requestUrl = new URL(serverUrl + req.url); + const pathComponents = requestUrl.pathname.split("/"); + + if (req.method == "GET") { + switch (pathComponents[1]) { + case "generateSecondView": + generateSecondView(req, res); + break; + default: + sendResponse(res, 200, "text/plain", "Welcome on our server."); + break; + } + } else if (req.method == "OPTIONS") { + sendResponse(res, 204, null, null); + } +}); + +server.listen(port, hostname, () => { + console.log("The server is running and listening at\n" + serverUrl); +}); + +function sendResponse(res, statusCode, contentType, data) { + res.statusCode = statusCode; + if (contentType != null) res.setHeader("Content-Type", contentType); + res.setHeader("Access-Control-Allow-Origin", "*"); + res.setHeader("Access-Control-Allow-Headers", "*"); + if (data != null) res.end(data); + else res.end(); +} + +function generateSecondView(req, res) { + let contentType = 'text/html'; + let filePath = '/Users/adnamaric/Desktop/grupp-4-project/client/secondView.html'; + + fs.readFile(filePath, (err, content) => { + if (err) { + res.writeHead(500); + res.end('Server Error'); + } else { + res.writeHead(200, { 'Content-Type': contentType }); + res.end(content, 'utf-8'); + } + }); +} \ No newline at end of file