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 is a block element?
<div> <img> <span>
<div>Web Programming and Development</div>
Which CSS code displays the text underlined?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
}
Click on the JavaScript function that can access other function after a specified time.
insertBefore() setTimeout() querySelector()
function someFunction() { alert("CoursesWeb.net"); }
setTimeout("someFunction()", 2000);
Click on the instruction that returns the number of items of a multidimensional array in PHP.
count($array) count($array, 1) strlen()
$food =["fruits" =>["banana", "apple"), "veggie" =>["collard", "pea"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
Node.js HTTP Module

Last accessed pages

  1. Date and Time in ActionScript 3 (10091)
  2. jQuery parent, children and nth-child() (13873)
  3. RegExp - Regular Expressions in ActionScript (4713)
  4. JavaScript strip_tags and stripslashes (8829)
  5. Complex Shapes with a single DIV and CSS (3711)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (643)
  2. The Mastery of Love (75)
  3. CSS cursor property - Custom Cursors (71)
  4. Read Excel file data in PHP - PhpExcelReader (67)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (48)