Nodejs Course

- Read the Query String from URL
- Split the Query String from URL

The Node.js HTTP module allows Node.js to receive and transfer data over the Hyper Text Transfer Protocol (HTTP).
To include the HTTP module, use the require() method:
const http = require('http');

Create a Node.js Web Server

The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.
Use the createServer() method to create an HTTP server:
//include the http module
const http = require('http');

//define constant for port
const port =8080;

//sets the server
const server = http.createServer((req, res)=> {
  res.writeHead(200, {'Content-Type':'text/plain'});
  res.write('Hello to me.');
  res.end();
});

//pass the port to server to listen to
server.listen(port, ()=> {
  console.log('Server running at //localhost:'+ port +'/');
});
The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 8080.
The res.writeHead() method include HTTP headers in response.
The first argument of the res.writeHead() method is the status code, 200 means that all is OK, the second argument is an object containing the response headers.
- If you want to output content with html tags, use header: {'Content-Type':'text/html'}.

I saved the code above in a file called "server.js" (in "test/" folder), then I initiate the file:.

- The Node.js server must be initiated in the "Command Line Interface" program of your computer.
To open the command line interface on windows, press the Start button and write "cmd" in the search field.

In the command line interface window I navigate to the folder that contains the Node.js application (E:/nodejs/), then, to initiate the "server.js" script, I write: "node test/server.js", and hit Enter.
In the command line interface window, node.js displays: "Server running at //localhost:8080/".
cmd start Node.js
- Now, the computer works as a server.

I open the browser, and I type in the address: http://localhost:8080
- Results:
browser Node.js
• To close the Node.js server, press Ctrl+C in the command line interface window, or just close that cmd window.

Read the Query String from URL

The function passed into the http.createServer() has a "req" argument that represents an object with request from the client (http.IncomingMessage object).
This object has a property called "url" which contains the part of the url that comes after the domain name.

For test, save the following code in a file called "demo_http_url.js" and initiate the file in the command line interface.
const http = require('http');

const server = http.createServer((req, res)=> {
  res.writeHead(200, {'Content-Type':'text/plain'});
  res.write(req.url);
  res.end();
});

server.listen(8080, ()=> {
  console.log('Server running at //localhost:8080/');
});
Once the Node.js server is started, if you access the server in your browser with two different addresses, you should see two different results.
For example, the address: //localhost:8080/coursesweb
- Produce this result:
/coursesweb
Accessing the address: //localhost:8080/marplo?id=1
- Will produce this result:
/marplo?id=1

Split the Query String from URL

You can use the build-in URL module to split the query string into readable parts. So, to can display different content according to data from URL query.
Example, split the query string into readable parts, and display content according to query parts.
//include http and url modules
const http = require('http');
const url = require('url');

//object width data for content
var cnt ={
  id:{1:'one', 2:'two', 3:'three'},
  nm:{'a':'Atom', 'e':'Electron', 'n':'Nothing'}
};

//create the server
const server = http.createServer((req, res)=> {
  res.writeHead(200, {'Content-Type':'text/html'}); //adds header to display html content

  //parse the url, get object with {name:value} from url query
  var q = url.parse(req.url, true).query;

  //get and write content from $cnt according to url data
  var cnt_id = cnt.id[q.id] ? cnt.id[q.id] :'No data for id';
  var cnt_nm = cnt.nm[q.nm] ? cnt.nm[q.nm] :'No data for nm';
  var add_cnt ='id '+ q.id +' = '+ cnt_id +'<br>nm '+ q.nm +' = '+ cnt_nm;

  res.write('<h3>'+ req.url +'</h3>'+ add_cnt);
  res.end();
});

server.listen(8080, ()=> {
  console.log('Server running at //localhost:8080/');
});
Save the code above in a file called "demo_url_query.js" and initiate the file with node in the command line interface.
Access in your browser the address: //localhost:8080/?id=1&nm=a
Will produce this result:

/?id=1&nm=a

id 1 = one
nm a = Atom

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag adds an image in web page?
<div> <img> <span>
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which of these CSS codes displays the text oblique?
font-style: italic; text-decoration: underline; font-weight: 500;
#id {
  font-style: italic;
}
Click on the jQuery function used to hide with animation a HTML element.
click() hide() show()
$(document).ready(function() {
  $(".a_class").click(function(){ $(this).hide("slow"); });
});
Click on the correctly defined function in PHP.
fname function() {} function fname() {} function $fname() {};
function fname($a, $b) {
  echo $a * $b;
}
Node.js HTTP Module

Last accessed pages

  1. jQuery Drag and Drop Rows between two similar Tables (12803)
  2. Star shapes with CSS (11170)
  3. Get and change IFrame content through a JavaScript script created in another IFrame (16387)
  4. Zodiac Signs JavaScript code (11027)
  5. Add text between two DIV tags (3872)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (319)
  2. Read Excel file data in PHP - PhpExcelReader (116)
  3. The Four Agreements (96)
  4. PHP Unzipper - Extract Zip, Rar Archives (91)
  5. The Mastery of Love (85)
Chat
Chat or leave a message for the other users
Full screenInchide