http.Server Is a
Based on the eventthe
The HTTP server
http.request Is a
HTTP client tool, used to
The HTTP server initiates the request, such as implementing Pingback or
Content to grab

Http.createserver creates one The HTTP Server instance

//app.js 
var http = require('http'); 
http.createServer(function(req, res) { 
 res.writeHead(200, {'Content-Type': 'text/html'}); 
 res.write('<h1>Node.js</h1>'); 
 res.end('<p>Hello World</p>'); 
}).listen(3000); 
console.log("HTTP server is listening at port 3000.");Copy the code

These are request objects (REQ) and response objects (RES). In the body of the function, res explicitly writes back the response code 200 (indicating that the request was successful), specifying that the response header is'Content-Type': 'text/html', and then writes the response body'<h1>Node.js</h1>', with res.end and send. Finally, the instance calls the Listen function to start the server and listen on port 3000.Copy the code

In addition to createServer, HTTP apis include server,request, etc.

Http. server and http.createServer have similar results

//httpserver.js 
var http = require('http'); 
var server = new http.Server(); 
server.on('request'.function(req, res) { 
 res.writeHead(200, {'Content-Type': 'text/html'}); 
 res.write('<h1>Node.js</h1>'); 
 res.end('<p>Hello World</p>'); 
}); 
server.listen(3000); 
console.log("HTTP server is listening at port 3000."); Copy the code

Http. Server’s events, which inherit from EventEmitter, provide the following events

  • Request: This event is triggered when a client request arrives, providing two parameters, req and res, respectively
ServerRequest and http.ServerResponse instances, representing request and response information.
  • Connection: This event is triggered when a TCP connection is established, providing a parameter socket, which is
Net.socket instance. Connection events are more granular than request events, because clients may send multiple requests within the same connection in keep-alive mode
  • Close: This event is triggered when the server is shut down. Note not when the user is disconnected.


http.ServerRequest

HTTP requests are generally divided into two parts: Request Header and Requset Body.

HTTP.ServerRequest controls the body of the request, and the following three events are used to control the content of the body

Data: This event is emitted when the request body data arrives. The event provides a parameter, chunk, which represents the connection

Data received. If the event is not listened for, the request body is discarded. The event may be adjusted
With The Times.
 end : This event is emitted when the request body data transfer is complete, after which no more data will arrive.
 close: This event is triggered when the user’s current request ends. Unlike end, if the user forces termination
Transfer, call close again.




 
Gets the content of the GET request

//httpserverrequestget.js 
var http = require('http'); 
var url = require('url'); 
var util = require('util'); 
http.createServer(function(req, res) { 
 res.writeHead(200, {'Content-Type': 'text/plain'}); 
 res.end(util.inspect(url.parse(req.url, true))); 
}).listen(3000);Copy the code

Type http://127.0.0.1:3000/user? in your browser name=byvoid&[email protected]

Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '? name=byvoid&[email protected]',
  query:
   [Object: null prototype] { name: 'byvoid', email: '[email protected]' },
  pathname: '/user',
  path: '/user? name=byvoid&[email protected]',
  href: '/user? name=byvoid&[email protected]' 
}Copy the code

Parse, the original path is parsed into an object, util.inspect is a conversion of any object to a string,query is the content of what we call a GET request, and the path is pathname.

Gets the POST request content

The contents of a POST request are all in the request body.
HTTP.ServerRequest does not have an attribute content for the request body, because waiting for the request body transfer might be
A time-consuming task, such as uploading a file. Most of the time, the content of the request body may be ignored, and a malicious POST request can consume a lot of server resources. So node.js doesn’t parse the request body by default, and you’ll need to do it manually if you need to.

//httpserverrequestpost.js 
var http = require('http'); 
var querystring = require('querystring'); 
var util = require('util'); 
http.createServer(function(req, res) { 
 var post = ' '; 
 req.on('data'.function(chunk) { 
 post += chunk; 
 }); 
 req.on('end'.function() { 
 post = querystring.parse(post); 
 res.end(util.inspect(post)); 
 }); 
}).listen(3000); 

Copy the code

Instead of returning information to the client in the request response function, the above code defines a POST variable, using the
In the
A closure holds the request body temporarilyThe information. Through the req
Data event listener functionEach time the request body data is received,
it
Add to the POST variableIn the. After the end event is triggered, the POST is resolved to queryString.parse
The actual POST request format is then returned to the client.


 http.ServerResponse

ServerResponse has three important member functions that return the response header, the response content, and end the request. WriteHead (statusCode, [headers]) : Sends the response header to the requesting client. StatusCode is an HTTP statusCode, such as 200 (request succeeded) or 404 (not found). Headers is an associative array-like object that represents each attribute of the response header. This function can only be called once in a request, and if it is not called, a response header is automatically generatedCopy the code

Response.write (data, [encoding]) : sends a response to the requesting client. Data is a Buffer, or string, that represents what is to be sent. If data is a string, you need to specify encoding to specify its encoding, which is UTF-8 by default. Response.write can be called multiple times before response.end is called.Copy the code

Response.end ([data], [encoding]) : ends the response to inform the client that all sending is complete. This function must be called once all the content to be returned has been sent. It takes two optional arguments that have the same meaning as Response.write. If this function is not called, the client is in a waiting state forever.Copy the code


The HTTP client

The HTTP module provides two functions: http.request and http.get. The function is to initiate requests to the HTTP server as a client

Http. request(options, callback) Initiates an HTTP request. It takes two arguments, option, which is an associative array-like object representing the request’s parameters, and callback, which is the request’s callback function.

callbackPass an argument, which is
HTTP. ClientResponse instance

http.requestReturn an instance of http.ClientRequest

//httprequest.js 
var http = require('http'); 
var querystring = require('querystring'); 
var contents = querystring.stringify({ 
 name: 'byvoid', 
 email: '[email protected]', 
 address: 'Zijing 2#, Tsinghua University'}); var options = { host:'www.byvoid.com', 
 path: '/application/node/post.php', 
 method: 'POST', 
 headers: { 
 'Content-Type': 'application/x-www-form-urlencoded'.'Content-Length' : contents.length 
 } 
}; 
var req = http.request(options, function(res) { 
 res.setEncoding('utf8'); 
 res.on('data'.function (data) { 
 console.log(data); 
 }); 
}); 
req.write(contents); 
req.end(); Copy the code

http.get(options, callback) automatically sets the request method to get without manually calling req.end().

//httpget.js 
var http = require('http'); 
http.get({host: 'www.byvoid.com'}, function(res) { 
 res.setEncoding('utf8'); 
 res.on('data'.function (data) { 
 console.log(data); 
 }); 
}); Copy the code