Example HTTP module in nodejs

Example create a web server :

 

//use http module

var http = require('http');

//create a server object:

http.createServer(function (req, res) {

  res.write('Hello World!'); //write a response to the client

  res.end(); //end the response

}).listen(8080); //the server object listens on port 8080

 

Run program with cmd:

 

C:\Nodejs> node httpModule.js

 

Go browser http://localhost:8080/

 

Hello World!

 

Example : add an htttp Header

 

//use http module

var http = require('http');

//create a server object:

http.createServer(function (req, res) {

  res.writeHead(200, {'Content-Type': 'text/html'}); // add an html header

  res.write('Hello World!'); //write a response to the client

  res.end(); //end the response

}).listen(8080); //the server object listens on port 8080

 

Run program with cmd:

 

C:\Nodejs> node httpModule.js

 

Go browser http://localhost:8080/

 

Hello World!

 

Example : get url

 

var http = require('http');

http.createServer(function (req, res) {

    res.writeHead(200, {'Content-Type': 'text/html'});

    res.write(req.url);

    res.end();

}).listen(8080);

 

Run program with cmd:

 

C:\Nodejs> node httpModule.js

 

Go browser http://localhost:8080/index.html

 

/index.html

 

Example: get param url

 

var http = require('http');

var url = require('url');

http.createServer(function (req, res) {

  res.writeHead(200, {'Content-Type': 'text/html'});

  var q = url.parse(req.url, true).query;

  var txt = q.year + " " + q.month;

  res.end(txt);

}).listen(8080);

 

Run program with cmd:

 

C:\Nodejs> node httpModule.js

 

Go browser http://localhost:8080/?year=2018&month=4

 

2018 4