NodeJs HTTP Server and client

Source: Internet
Author: User
Tags event listener response code terminates

The node. JS Standard library provides an HTTP module that encapsulates an efficient HTTP server and a simple HTTP client. http. Server is an event-based HTTP server whose core is implemented by the node. JS downlevel C + + section, and the interface is packaged in JavaScript for high performance and simplicity. Http.request is an HTTP client tool that initiates requests to an HTTP server, such as implementing pinkback or fetching content.

HTTP Server

http. Server is an HTTP server object in the HTTP module, and all HTTP protocol-based systems, such as Web sites, social applications, and even proxy servers, are based on HTTP. js. implemented by the server. It provides a package of low-level API, just flow control and simple message parsing, all the high-level functions are through its interface to achieve. Here we use HTTP to implement a server:

// App.js var http = require (' http '); http.createserver(function  (req, res) {    Res.writehead ( {' Content-type ': ' text/html '});    Res.write (' );    Res.end (' <p>hello world</p> ');}). Listen,console.log (' HTTP server is listening at Prot 3000. ');

Http.createserver creates an instance of Http.server and takes a function as an HTTP request handler function. The function accepts two parameters, namely the Request object req and the response object Res. In the function body, the res appears to write back the response code 200 (indicating a successful request), specifying the response header as ' Content-type ': ' text/html ', and then writing to the response body '

1.http. Events for Server

http. Server is an event-based HTTP server, all requests are encapsulated as separate events, and developers only need to write a response function on its events to implement all the functions of the HTTP server. It inherits from Eventemitter and provides the following several events.

    • Request: When the client request arrives, the event is triggered, providing two parameters req and res, respectively http. An instance of Serverrequest and http.serverresponse that represents the request and response information.
    • Connection: When a TCP connection is established, the event is triggered, providing a parameter socket, which is net. The instance of the socket. The granularity of the connection event is greater than the request because the client may send multiple requests within the same connection in keep-alive mode.
    • Close: The event is triggered when the server shuts down. Note Not when the user connection is disconnected.

In addition, there are checkcontinue, upgrade, Clienterror events, which we do not need to worry about, but only when implementing a complex HTTP server.

The most common is the request event, so HTTP provides a shortcut: Http.createserver ([Requestlistener]), The function is to create an HTTP server and use Requestlistener as the listener function for the request event. It shows how to implement this:

 // httpserver.js  var  http = require (' http '  var  server = new   HTTP. Server (); Server.on ( ' request ', function   $, {' Content-type ': ' text/html ' });    Res.write ( ' ); Res.end ( ' <p>hello world</p> ' );}); Console.log ( ' HTTP server is listening at prot. '); 

2.http. Serverrequest
http. Serverrequest is the message of HTTP requests and is the focus of the backend developers. He is generally made up of HTTP. The server's request event is sent as the first parameter, usually referred to as a request or req. HTTP requests can generally be divided into two parts: the request header and the request body. The above content can be read immediately after the request header resolution is completed because of short length. While the request may be relatively long, it takes a certain amount of time to transmit, so HTTP. Serverrequest provides 3 events to control the transfer of the request body.

    • Data: The event is triggered when the request body data arrives. The event provides a parameter, chunk, that represents the data received. If the event is not monitored, the request body will be discarded. The event may be called multiple times.
    • End: When the request body data transfer is complete, the event is triggered and the wait will no longer have data coming.
    • Close: The event is triggered at the end of the user's current request. Unlike end, if the user forcibly terminates the transfer, it is also called close.

Properties of the Serverrequest

Complete: Whether the client request has been sent

Httpversion:http protocol version, 1.0 or 1.1 in the same range

Method:http request methods, such as GET, POST, PUT, delete, etc.

URL: The original request path, such as/static/image/x.jpg or/user?name=byvoid

Headers:http Request Header

Trailers:http request tail (uncommon)

Connection: The current HTTP connection socket, is net. Examples of Scoket

Alias of the Socket:connection property

Alias of the Client:client property

3. Get the GET Request content

Because the GET request is embedded directly in the path, the URL is the complete request path, including the? The following section, so you can manually parse the following contents as parameters of the GET request. The parse function in the URL module of node. JS provides this functionality, such as:

// Httpserverrequestget.js var http = require (' http '); var url = require (' URL '); var util = require (' util '); Http.createserver (function  (req, res) {    Res.writehead ($, {' Content-type ': ' Text/plain '});     true )));}). Listen (3000);

Access Http://127.0.0.1:3000/user?name=byvoid&[email protected] in the browser, you can see the results returned by the browser:

{     '? Name=byvoid&[email protected] ',    query: {             ' byvoid ',         ' [email Protected] '     },    '/user ',    '/user?name=byvoid&[email protected] ',    '/user?name=byvoid&[email protected] ' }

With Url.parse, the original path is parsed into an object, where query is the content of what we call a GET request, and the path is pathname.

4. Get POST Request content

The contents of the POST request are in the request body. http. Serverrequest does not have a property content for the request body, because waiting for a request body transfer can be a time-consuming task, such as uploading a file. And many times we may not need to ignore the content of the request body, malicious post requests will greatly consume the resources of the server. So node. JS does not parse the request body by default, and it needs to be done manually when you need it. The implementation method is as follows:

//Httpserverrequestpost.jsvarHTTP = require (' http ');varQueryString = Require (' querystring '));varUtil = require (' util ')); Http.createserver (function(req, res) {varPost = '; Req.on (' Data ',function(chunk) {post+=Chunk;    }); Req.on (' End ',function() {post=Querystring.parse (POST);    Res.end (Util.inspect (POST)); });}). Listen (3000);

Instead of returning information to the client in the request response function, the above code defines a post variable for staging the request body information in the closure. Through the Req Data event listener function, each time a request body is accepted, it is accumulated into the post variable. After the end event is triggered, the post is parsed into the true POST request format via Querystring.parse and then returned to the client.
* Note: Do not use this simple method to get a POST request in a real production application because it has serious efficiency problems and security issues, which is just an example of helping to understand.

5.http. Serverresponse

http. Serverresponse is the information returned to the client, which determines the results that the user can eventually see. It is also by HTTP. The server's request event is sent as a second parameter, generally referred to as response or Res.

http. Serverresponse has three important member functions for returning the corresponding header, corresponding content, and closing the request.

    • Response.writehead (StatusCode, [headers]): Sends a response header to the requesting client. StatusCode is an HTTP status code such as 200 (request succeeded), 404 (Not Found), and so on. Headers is an object that resembles an associative array that represents each property of the response header. The function can be called at most once in a request, and a response header is automatically generated if not called.
    • Response.Write (data, [encoding]): Sends the response content to the requesting client. Data is a buffer or string that represents the content to send. If data is a string, you need to specify encoding to describe how it is encoded, by default, Utf-8. The Response.Write can be called multiple times before the Response.End call.
    • Response.End ([Data], [encoding]): Ends the response, informing the client that all sends have been completed. When all the content to be returned is sent, the function must be called once. It accepts two optional parameters, the same meaning and Response.Write. If you do not call this function, the client is always in a wait state.

HTTP Client

The HTTP module provides two functions http.request and http.get, which function as a client to initiate a request to an HTTP server.

    • Http.request (options, callback) initiates an HTTP request. Accepts two parameters, options is an object that resembles an associative array, represents the requested parameter, and callback is the requested callback function. The parameters used in the options are as follows:
    1. Host: The domain name or IP address of the requesting web site
    2. Port: Ports for requesting a Web site, default 80
    3. Method: Request a hair, default is get
    4. Path: The relative root path of the request, default is "/". The querystring should be included. such as/search?query=byvoid.
    5. Headers: An associative array object that is the content of the request header.

Callback passes a parameter, which is HTTP. An instance of Clientresponse.

Http.request returns an instance of a http.clientrequest.

Here is a code to send a POST request via Http.request:

//Httprequest.jsvarHTTP = require (' http ');varQueryString = Require (' querystring '));varContents =querystring.stringify ({name:' Byvoid ', Email:' [Email protected] ', Address:' Address1 '});varOptions ={host:' Www.byvoid.com ', Path:'/application/node/post.php ', Method:' POST ', headers: {' Content-type ': ' application/x-www-form-urlencoded ',        ' Content-length ': Contents.length}};varreq = http.request (options,function(res) {res.setencoding (' Utf-8 '); Res.on (' Data ',function(data) {Console.log (data); });}); Req.write (contents); Req.end ();
    • The Http.get (options, callback) HTTP module also provides a more convenient way to handle get requests: Http.get. It is a simplified version of Http.request, the only difference being that Http.get automatically sets the request method to a GET request and does not require a manual call to Req.end ().
// Httpget.js var http = require (' http 'function  (res) {    res.setencoding (' utf-8 ');    Res.on (function  (data) {        console.log (data);    } );
    1. http. Clientrequest

http. Clientrequest is an object produced by Http.request or http.get that represents an HTTP request that has been generated and is in progress. It provides a response event, which is the binding object of the callback function specified by the second parameter of Http.request or Http.get. We can also display the listener function to bind this event:

// Httpresponse.js var http = require (' http '); var req = Http.get ({host: ' ww.byvoid.com '}); Req.on (function  (res) {    Res.setencoding (' utf-8 ');    Res.on (function  (data) {        console.log (data);    });})

http. Clientrequest, like Http.serverresponse, also provides the write and end functions for sending the request body to the server, typically for post, put, and so on. After all writes have been completed, the End function must be called to notify the server, otherwise the request is invalid. http. Clientrequest also provides the following functions.

    • Request.about (): Terminates the request being sent.
    • Request.settimeout (timeout, [callback]): Sets the request time-out period, with a timeout of milliseconds. When the request times out, the callback will be called.

In addition, functions such as request.setnodelay ([Nodelay]), request.setsocketkeepalive ([Enable], [InitialDelay]) are also available.

2.http. Clientresponse

http. Similar to Http.serverrequest, Clientresponse provides three events, data, end, and close, which are triggered at the end of arrival, transfer, and connection, where the data event passes a parameter chunk that represents the received information.

http. The Clientresponse also provides several special functions.

    • Response.setencoding ([encoding]): Sets the default encoding, which is encoded with encoding when the data event is triggered. The default value is NULL, which is not encoded and stored as buffer. Common code is UTF8.
    • Response.pause (): Pause to receive data and send events to facilitate the download function.
    • Response.resume (): Resumes from a paused state.

NodeJs HTTP Server and client

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.