Get in touch
or send us a question?
CONTACT

[Node.js Tutorials for Beginners] – Unit 7: Create server Node.js with HTTP module

thumbnail

Table of Contents

1. What HTTP Module?

2. Create server with HTTP module

3. Some Examples

4. Methods and Properties in request and response

1. What HTTP Module

The http module has a function, createServer, which takes a callback and returns an HTTP server.

On each client request, the callback is passed in two arguments the incoming request stream and an outgoing server response stream.

To start the returned HTTP server, call its listen function passing in the port number.

2. Create server with HTTP module

Example: require module http

var http = require(‘http’);

Example: Create a server run port 8081

var http = require(‘http’);

http.createServer().listen(8081);

3. Some Examples

The following code provides a simple server that listens on port 8081 and simply returns “Hello World” on every HTTP request.

First, create file unit7.js

var http = require(‘http’);

http.createServer(function (request, response){

response.write(‘Hello World!’);

response.end();

}).listen(8081);

console.log(‘Server running at http://localhost:8081/‘);

To test the server, simply start the server using Node.js

$ node unit7.js

Server running at http://localhost:8081/

Then test an HTTP connection using any browsers:

http://localhost:8081/

– or http://127.0.0.1:8081/

To exit the server, simply press Ctrl+C in the window where the server was started.

4. Methods and Properties in request and response

writeHead()

The writeHead() function sets the type of data the server wants to return.

Example: Set server return is a HTML page

var http = require(‘http’);

http.createServer(function (request, response){

response.writeHead(200, {‘Content-Type’: ‘text/html’});

response.write(‘Hello World!’);

response.end();

}).listen(8081);

console.log(‘Server running at http://localhost:8081/’);

write()

This function sets the content that the server wants to return to the browser, this content can be text, HTML code.

Example: Return a HTML page has tag H1 contain line text Hello World

var http = require(‘http’);

http.createServer(function (request, response){

response.writeHead(200, {‘Content-Type’: ‘text/html’});

response.write(‘<html>’);

response.write(‘<head>’);

response.write(‘<title>Hello Page</title>’);

response.write(‘</head>’)

response.write(‘<body><h1>Hello World!</h1></body>’);

response.write(‘</html>’)

response.end();

}).listen(8081);

console.log(‘Server running at http://localhost:8081/‘);

Output:

url

This property contains parameters in the URL that the client sends to server.

Example:

var http = require(‘http’);

http.createServer(function (request, response){

var param = request.url;

response.write(param)

response.end();

}).listen(8081);

console.log(‘Server running at http://localhost:8081/’);

Thank you for reading!