Index
Concept


Web server:


In this example, we'll first code a web server, and then we'll test it by sending a request to it from a web browser.

Example


>npm init
Use the npm install command to install the public package http-status-codes
>npm install http-status-codes
Create file "hello-world.js" with source shown.

Keywords:

//hello-world.js

const
	http = require('http'),
	httpStatusCodes = require('http-status-codes'),
	port = 3000;
	
const createCallbackFct = (req, res) => {
	res.writeHead(httpStatusCodes.OK, {'Content-Type': 'text/html'});
	res.write('<h1>Hello World!</h1>');
	res.end();
}

const listenCallbackFct = () => console.log(`Server started on port: ${port}`);

const server = http.createServer(createCallbackFct);
server.listen(port, listenCallbackFct);
>node hello-world
  • Open a web browser.
  • Go to the address bar
  • Enter "http://localhost:3000/" in the address bar
  • Or, you can click directly on the url shown here to the right


http://localhost:3000/

Hello World!



References