Based on the eventthe
The HTTP server
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
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
- Connection: This event is triggered when a TCP connection is established, providing a parameter socket, which is
- Close: This event is triggered when the server is shut down. Note not when the user is disconnected.
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
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
//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
A closure holds the request body temporarilyThe information. Through the req
Data event listener functionEach time the request body data is received,
Add to the POST variableIn the. After the end event is triggered, the POST is resolved to queryString.parse
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
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
//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