Node.js HTTP server examples
Before making an Node.js application using express.js package, tried to make simple http server examples without the package. It was fine to check what happens under the hood in server side JS.
1 Simple server
Simple server using http.createServer(request, response)
|
|
Start server:
|
|
Then you can access to the web page from browser by URL: http://localhost:3000/
Console output shows:
|
|
2 Simple server, parsing request
Simple server + parse request url and headers in JSON format
|
|
Then you can access to the web page from browser by URL: http://localhost:3000/
Console output shows:
|
|
3 Route requested url
Route requested url to response
|
|
Then you can access web content:
http://localhost:3000
> “Hello, Welcome! "http://localhost:3000/info
> “Info is here”http://localhost:3000/contact
> “Contact Us”http://localhost:3000/about
> “About Us”http://localhost:3000/hello
> “Say hello by emailing us here(link)”http://localhost:3000/error
> “Sorry, the page are you looking for is not here”
And console output shows requested URL and Headers response status code like:
|
|
4 Serve html content
Serve html file by fs
package
|
|
Then you can access web content:
http://localhost:3000/index
> “Welcome!”
If you access to the other url like:
http://localhost:3000
http://localhost:3000/index.html
http://localhost:3000/info
“Sorry, Not Found”
5 Serve html content based on routing
Serve html file + register handlers for routing requested url to response
|
|
Then you can access web content (html pages in /views/ directory)
Then you can access web content:
http://localhost:3000/index.html
> “Welcome!”http://localhost:3000/contact.html
> “Please contact to us from here”- not existing endpoint (
http://localhost:3000/co.html
) > “No such file exists”