Module 07: Server Hosted Site
This project is made of two parts. The first part is a very simple site that uses localStorage to operate a login menu. The second part is a script that creates a server and runs the site on it.
Part 1: The site
This site uses a couple of text boxes and a button for a login. You put in a username and password and when you hit Login, it sends the values to localStorage. It then uses jQuery to hide the text boxes and show a div with the information in localStorage displayed. If you close the window and open it, it should remember the last user. If they hit log out, the user and password is wiped from the localStorage. If you close the window and come back, it displays the text boxes. This isn't the best way to make a login but it showcases how to use localStorage.
You can try out the page by itself.Part 2: The Script
This script starts off with getting the HTTP and File System modules.
const http = require('http');
const {readFileSync} = require('fs');
Now that I have the access to the mdoules, I use readFileSync to read the files that make up the site.
const indexpg = readFileSync('./site/index.html');
const myjs = readFileSync('./site/index.js');
const mycss = readFileSync('./site/style.css');
Then I create the server. We use the constant url to get the requested URL. After that is a series of if/elses that write either a file from the site or a custom message. The last else is to catch an incorrect url. It displays an error message written in HTML.
const server = http.createServer((req,res)=>{
const url = req.url;
if(url === '/'){
res.writeHead(200,{'content-type':'text/html'});
res.write(indexpg);
res.end();
} else if(url === '/index.js'){
res.writeHead(200,{'content-type':'text/javascript'});
res.write(myjs);
res.end();
}else if(url === '/style.css'){
res.writeHead(200,{'content-type':'text/css'});
res.write(mycss);
res.end();
} else {
res.writeHead(404,{'content-type':'text/html'});
res.write(' <h1>Oops. Page not found.</h1>');
res.end();
}
});
Finally we setup the port number the server is operating at and print a message to the console to provide user feedback.
server.listen(8080);
console.log('Server reached');
Below is the command you will use in the command prompt and the response. Then, if you go to http://localhost:8080/ the site described in part one will be there and functioning.
>node script.js
>Server reached