JAVA SCIPT - Responding to a Simple Browser Request - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCIPT - Responding to a Simple Browser Request - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, March 7, 2019

JAVA SCIPT - Responding to a Simple Browser Request

Responding to a Simple Browser Request


Problem

You want to create a Node application that can respond to a very basic browser request.

Solution 

Use the built-in Node HTTP server to respond to requests:
// load http module
var http = require('http');
// create http server
http.createServer(function (req, res) {
 // content header
 res.writeHead(200, {'content-type': 'text/plain'});
 // write message and signal communication is complete
 res.end("Hello, World!\n");
}).listen(8124);
console.log('Server running on 8124/');


EXPLAIN

The simple text message web server response to a browser request is the “Hello World” application for Node. It demonstrates not only how a Node application functions, but how you can communicate with it using a fairly traditional communication method: requesting a web resource. Starting from the top, the first line of the solution loads the http module using Node’s require() function. 

This instructs Node’s modular system to load a specific library resource for use in the application—a process I’ll cover in detail. The http module is one of the many that comes, by default, with a Node installation. Next, an HTTP server is created using http.createServer(), passing in an anonymous function, known as the RequestListener with two parameters. 

Node attaches this function as an event handler for every server request. The two parameters are request and response. The request is an instance of the http.IncomingMessage object and the response is an instance of the http.ServerResponse object. The http.ServerResponse is used to respond to the web request. 

The http.Incoming Message object contains information about the request, such as the request URL. If you need to get specific pieces of information from the URL (e.g., query string parameters), you can use the Node url utility module to parse the string. demonstrates how the query string can be used to return a more custom message to the browser. 


Parsing out query string data



// load http module
var http = require('http');
// create http server
http.createServer(function (req, res) {
 // get query string and parameters
 var query = require('url').parse(req.url,true).query;
 // content header
 res.writeHead(200, {'content-type': 'text/plain'});
// write message and signal communication is complete
 var name = query.first ? query.first : "World";
 res.end("Hello, " + name + "!\n");
}).listen(8124);
console.log('Server running on 8124/');
A URL like the following:
http://shelleystoybox.com:8124/?first=Reader


results in a web page that reads “Hello, Reader!”


Notice in the application that I used require() in the code, and chained methods di‐ rectly on the returned module object. If you’re using an object multiple times, it makes sense to assign it a variable at the top of the application. However, if you’re only using the module object once, it can be more efficient to just load the object in place, and then call the methods directly on it. In the code, the url module object has a parse() method that parses out the URL, returning various components of it (href, protocol, host, etc.).

If you pass true as the second argument, the string is also parsed by another module, querystring, which returns the query string as an object with each parameter as an object property, rather than just returning a string. In both the solution , a text message is returned as page output, using the http.ServerResponse end() method. I could also have written the message out using write(), and then called end():

res.write("Hello, " + name + "!\n");
res.end();

The important takeaway from either approach is you must call the response end() method after all the headers and response body have been sent. Chained to the end of the createServer() function call is another function call, this time to listen(), passing in the port number for the server to listen in on. This port number is also an especially important component of the application.

Traditionally, port 80 is the default port for most web servers (that aren’t using HTTPS, which has a default port of 443). By using port 80, requests for the web resource don’t need to specify a port when requesting the service’s URL. However, port 80 is also the default port used by our more traditional web server, Apache. If you try to run the Node service on the same port that Apache is using, your application will fail.

The Node application either must be standalone on the server, or run off a different port. You can also specify an IP address (host) in addition to the port.

Doing this ensures that people make the request to a specific host, as well as port. Not providing the host means the application will listen for the request for any IP address associated with the server. You can also specify a domain name, and Node resolves the host.

There are other arguments for the methods demonstrated, and a host of other methods, but this will get you started. Refer to the Node documentation for more information.


No comments:

Post a Comment

Post Top Ad