In node.js both client program and server program are written in Javascript. In order to create server you can use http module of node.js. We will discuss with a simple program how client server program is done in node.js.

First we have to setup the server.

  • Node.js provides an httpmodule
  • This http module is used to create an HTTP server.
  • this HTTP server which listens at port.

Create a file named index.js in node.js

  • var http = require(‘http’);
  • http.createServer(function (req, res){
  • res.write(‘WELCOME TO MY FIRST PROGRAM!’);
  • res.end(); //end the response
  • }).listen(8080);

Set HTTP Header in Node.js

  • var http = require(‘http’);
  • http.createServer(function (req, res) {
  • res.writeHead(200, {‘Content-Type’: ‘text/html’});  // On this line we set up http header in Node.js
  • res.write(‘My first program!’);
  • res.end();}).listen(8080);

Split query string in Node.js

We use the url module to split the query string .

  • varhttp = require(‘http’);
    varurl = 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.product + ” ” + q.weight;
    res.end(txt);
    }).listen(8080);

http://localhost:8080/?product=p&weight=45

163total visits,1visits today