Index
Overview


A video that accompanies the page is here....

And a video that shows how to run the example code is here....

A prerequisite to this Routing work is understanding URL path and query as described in HTTP.

Routing means taking a URL from a request and routing it to the web server code that will handle the request.

Routing Table and Endpoints


You'll hear the word endpoint frequently when working with web servers and URLs. Like many software engineering terms it is not tightly defined. We'll try to explain the essence of it here.

Path and ParamsURL Relative Endpoint
(URL path)
Functional Endpoint
(method/function)
/convert/temperature?unit=c&value=10/convert/temperatureconvert
/convert/length?unit=m&value=2/convert/lengthconvert
/translate/english?word=hello/translate/englishtranslateEnglish

The end point means that the request has traveled the "www" and finally reached its final (end) destination -- which is the functional endpoint that will handle it (i.e., our code).

Example


We learned in the HTTP section how to get the URL path. We use that path to route the request.

The following will show the code used to handle the URL paths in the routing table above.

For the next steps, we'll assume this URL:

http://localhost:3000/convert/length?unit=m&value=2


This URL be routed to logic that will convert a length of 2 meters (m) to other length units.

We first get the path and then look for endpoint matches to route to the appropriate function or method.

This is the essence of routing: URL endpoint to functional endpoint.
route() {
	const path = this.url.path();
	if (path === '/convert/temperature')
		this.convert(TemperatureConverter);
	else if (path === '/convert/length')
		this.convert(LengthConverter);
	else if (path === '/translate/english')
		this.translateEnglish();
	else
		log(`URL Path not handled: ${path}`);
}
We are now in a functional endpoint "convert".

We grab the query params unit and value, and then construct a model, and serve the results.
convert(converterClass) {
	const
		query = this.url.query(),
		unit = query.unit,
		value = query.value;
	if (!this.validateParam('unit', unit) || !this.validateParam('value', value))
		return;
	const converter = new converterClass(unit, value);
	this.serveConversionResults(converter.getResults());
}
The "serve" method logic is familiar -- writing the results as HTML to the reponse.

The result is a collection of value-unit pairs.
serveConversionResults(arrayResults) {
	//serve result to client/consumer
	const res = this.response;
	res.writeHead(statusCodes.OK, htmlContentType);
	//result is an array
	for (let pair of arrayResults)
		res.write(`${pair.value} ${pair.unit}` + br);
	res.end();
}
Web browser client showing results
2 m
6.56168 ft
2000 mm
200 cm
0.002 km
78.74016 in
0.00124 mi
2.18723 yd
Here is the example project source code.

The project will require an npm init, and then npm installs of two modules: "http-status-codes" and "url-wrapper".