Html on this server

Web basics: sending HTML, CSS and Javascript content through HTTP

Now that we have an HTTP server sending plain text content, it’s time to enhance the server so it can respond in a more appropriate content type for Web browsers.

Web standards

In the very beginning of Web, websites did not follow a standard, besides such constraints could take users to a bad navigation experience. To mitigate this, the web standards model was created, which then became the foundation of Web, composed by the building blocks HTML, CSS and Javascript. The idea behind these standards is to establish a well-defined set of elements, rules and behaviours for webpages hence providing a better experience for users navigating on Web.

Enhance the HTTP server to respond HTML content

Aiming to respond HTML, we should do no more than using HTML structured elements. Let’s change our test to expect HTML content from the server response:

require 'socket' require 'test/unit' class ServerTest  Test::Unit::TestCase def test_client_42 server = TCPSocket.open('localhost', 80) request = "GET /users/42 HTTP/1.1\r\n\r\n" server.puts(request) response = '' while line = server.gets response += line end assert_equal "HTTP/1.1 200\r\nContent-Type: text/html\r\n\r\n

Hey, 42!

\n", response server.close end end
HTTP/1.1 200\r\n Content-Type: text/html\r\n \r\n 

Hey, 42!

. loop do client = socket.accept first_line = client.gets verb, path, _ = first_line.split if verb == 'GET' && matched = path.match(/^\/customers\/(.*?)$/) user_id = matched[1] response = "HTTP/1.1 200\r\nContent-Type: text/html\r\n\r\n

Hey, #user_id>!

"
client.puts(response) end client.close end .

Important to note that the header Content-Type: text/html is very strict then necessary for some web browsers. Now, run the test using make test which should pass. Additionally, test the HTML using curl:

curl http://localhost/users/42 => 

Hey, 42!

Alt Text

Open the web browser at http://localhost/users/42 too and see the content being rendered properly:

Unlike curl, a web browser is capable of using the header Content-Type to render the correct type. Try removing the header from the server response and see that the text will be displayed in plain text:

CSS to "rule" them all 🥁

What if we wanted to add layout characteristics to our HTML elements? For instance, how to assign the color red to the h1 title? We can use CSS to apply layout rules.

CSS inline

The most common, despite not encouraged way to write CSS is inline along with the HTMl element, by using the style HTMl attribute:

body = "

Hey, #user_id>!

"
status = 200 response = "HTTP/1.1 #status>\r\nContent-Type: text/html\r\n\r\n#body>" client.puts(response) .

CSS in head

Alt Text

Adding behaviour with Javascript

Javascript is a programming language used to add runtime behaviour to the HTML elements. Runtime behaviour means when the HTMl content was already served by the server, as the server closed the connection with the client (web browser), so that the client can leverage on the solely power dynamycs of Javascript. It can manipulate at various ways, since adding new elements to the page (DOM), removing existing ones, changing their layout rules (CSS), communicating to other websites and so on. Every modern web browser comes with a runtime tool for Javascript, so the easiest way to start is opening the web browser developer tools and start using it to learn and experiment.

Changing the element color using Javascript

Let's give the user the ability to click on a button that will change the title's color to blue. Initially, our HTML will look like this:

  h1  color: red; >   Hey, 42!  onclick="changeTitleColor()">Change color to blue function changeTitleColor()  let title = document.querySelector('h1'); title.style.color = 'blue'; >  
  • all the Javascript code will be placed inside the HTML tag script
  • the button element has an inline Javascript listener, the onclick , which triggers the function changeTitleColor when the button is clicked by the user.

Isolating HTML content from CSS and Javascript

As for the CSS inline, HTML content should not know about CSS rules nor Javascript listeners. Being isolated, it can be reused across multiple HTML files once the application starts growing more.

As such, the representation of our HTML content could be as follows:

  h1  color: red; >   Hey, 42!  isolated from CSS flavour button>Change color to blue  isolated from Javascript flavour script> function changeTitleColor() < let title = document.querySelector('h1'); title.style.color = 'blue'; >document.querySelector('button').addEventListener('click', changeTitleColor); 
  • CSS placed under head
  • HTML isolated from CSS and Javascript
  • Javascript placed under script

This approach will allow us in the future to even import CSS and Javascript from different files*, so that we would end up having a file for HTML, other for CSS and yet another for Javascript!

Let's see it in action. In the server.rb , we define a "string template" for our structured HTMl, which now is much more rich and complex:

require 'socket' socket = TCPServer.new(80) template = STR   h1 

Hey, >!

STR

Note the > "tag". It's not a valid HTML tag, which would make the web browser to render it in plain text. But we want to replace it using the real userID, before the server sends the HTMl to the client.

In Ruby, we can do this by using gsub :

body = template.gsub(">", user_id) 

The final implementation

After all of those minor improvements, our server implementation looks like the following:

require 'socket' socket = TCPServer.new(80) template = STR   h1 

Hey, >!

STR loop do client = socket.accept first_line = client.gets verb, path, _ = first_line.split if verb == 'GET' && matched = path.match(/^\/customers\/(.*?)$/) user_id = matched[1] body = template.gsub(">", user_id) response = "HTTP/1.1 200\r\nContent-Type: text/html\r\n\r\n#body>" client.puts(response) end client.close end

Then, after opening it in the web browser, we have the result:

Wrapping up

Understanding how web works is very important for web developers. In this post we learned the third part of the serie of "Web basics 101", which consists of sending HTML content through HTTP.

HTML is no more than a simple string content following a standard format for webpages. Along with CSS and Javascript being sent over HTTP, they are all the foundation of Web powering modern websites with rich content and usability.

Источник

How to run html file on localhost

Illustration of Local HTML with NODEjs, PHP and Python

Normally when I want to view a HTML file, I just right-click it and choose to open it with a web browser. However, I wanted to run a html page using localhost. I went online, researched and found 3 methods that works.

  1. What is localhost and where can I access it.
  2. Local server. What is that?
  3. Methods of accessing HTML page on localhost
  • Localhost using python
  • Local host using PHP
  • Localhost using Node JS
  1. Why use localhost to host a html page
  2. When to use localhost to run a html page

Sometimes, you want to see how the HTML page would work as if it were on a server. And that’s where localhost and local server comes in. Let me explain.

What is localhost and where can I access it?

Localhost is the url on a computer that points to itself. The computer does not need the internet for the address to work since it only checks on itself.

To access localhost, you write localhost or 127.0.0.1 on the browser.

When you try to access localhost now, you will find nothing there. or see default apache page(if apache is installed).You need to host a html file on a server(on your computer) that serves a page on localhost.

Local server. What is that?

A local server is a server running on the computer you are working on. It works like any other server. You need to start the server for it. when the server is ready, it can be accessed on a specific url.

Once the server is ready, accessing the localhost on a browser will display the page or folder served by the server.

There are three ways I have tried that worked for me and I will show you how in the next few section. These are:

method 1: Use python to run a HTML page on localhost

Python has a in-built server that you can run with a single command.

Check if python is installed

For this method to work, you need to have python installed on your computer. You can check if you have python installed on Windows computer by checking if it is in your programs list.

For Ubuntu, Mac OS X and Debian, Python comes preinstalled. You can easily check if you have python in your system by typing python --version on the terminal.

Running a html page on localhost UNIX(Linux and Mac OS X)

  1. Open the terminal on your system.
  2. Navigate to the folder containing the HTML file.
  3. Run the command: python -m SimpleHTTPServer

You will see a log with where you can access the page

Serving HTTP on 0.0.0.0 port 8000

Screenshot of terminal and browser on locahost python

You can set a specific port number by adding the port numuber to the command. The command on the terminal becomes : python -m SimpleHTTPServer 6734

Then on the browser type localhost:6734 as the URL.

2: Use PHP to run an inbuilt localhost server

Php also has an i built web server that can run your files on local host.

Check if PHP is installed

PHP is usually installed when installing a local LAMP, WAMP or LAMP server setup. You can easily check if you have python in your system by typing: php --version

If PHP is installed, the output will be:

PHP 7.2.15-0ubuntu0.18.04.2 (cli) (built: Mar 22 2019 17:05:14) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.2.15-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies

Othewise, if you can not get something like this on windows, read you can read how to check if PHP is installed and troubleshooting. You can Read on how to install php on Ubuntu or Windows or Mac OS X.

  1. Open the terminal on your system.
  2. Navigate to the folder containing the HTML file.
  3. Run the command: php -S 0.0.0.0:8000 or php -S localhost:8000 on the terminal. You get the following output:
Listening on http://localhost:8000 Document root is /home/ndugu/Documents/portfolio/activity-logger Press Ctrl-C to quit.

Screenshot of terminal and browser on localhost php

3: Use Node js to run html file on local host

If you have nodejs and npm installed,then you can install a http server by running this command in the terminal:

Navigate to folder where you have html file in terminal and type:

To run a specific html file, type:

When to use localhost to run a html page

When you are building and testing a web project that is in your laptop that must run on a server. Some projects require that you have a local server running in your laptop. Localhost is just a way of accessing the server that you are currently working on.

I still can’t get the server to work. What should I look for?

Make sure your are using a colon : after localhost and not a forward slash / .

Most times you will see localhost url written as localhost:8000 or any other 4 digit number. This number is called a port number. The port number allows you to run many pages on localhost with different port numbers at the same time.

When you try to access localhost now, you will find nothing there. You need to host a html file on a server(on your computer) that serves a page on localhost. Once the server is ready, accessing the localhost on a browser will display the page or folder served by the server.

If you are new to HTML, you can learn and practice HTML on this website.

author

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.

Front End Developer Newsletter

Receive a monthly Frontend Web Development newsletter.
Never any spam, easily unsubscribe any time.

About

If you are just starting out you can test the waters by attempting the project-based HTML tutorial for beginners that I made just for you.

Okay, you got me there, I made it because it was fun and I enjoy helping you on your learning journey as well.

You can also use the HTML and CSS projects list as a source of projects to build as you learn HTML, CSS and JavaScript.

Start understanding the whole web development field now

Stop all the confusion and start understanding how all the pieces of web development fit together.

Never any spam, easily unsubscribe any time.

Recent Posts

Источник

Читайте также:  Python numpy complex numbers
Оцените статью