Http.server is an event-based HTTP server, all requests are encapsulated as separate events, developers only need to write a response function to his event to implement all the functions of the HTTP server, it inherits from the Eventemitter
3. http. Serverresponsehttp. Serverresponse is the information returned to the client, which determines the result that the user can finally see, and 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 response headers, responding to content, and closing requests:
(1) response.writehead (Statscode,[headers]): Sends a response header to the requesting client, StatusCode is an HTTP status code such as 200 (request succeeded), 404 (not Found), etc. Headers is an object that resembles an associative array, representing each property of the response header, which can be called at most once in a request, and automatically generates a response header if it is not called.
(2) Response.Write (data,[encoding]): Send the response content to the requesting client, data is a buffer or a string representing the content to be sent, if data is a string, you need to specify the encoding encoding method, The default is Utf-8, called before Response.End, Response.Write can be called multiple times;
(3) Response.End ([data],[encoding]): End the response, tell the client that all the send has completed, when all the content to be returned is sent, the function must be called once, he can accept two parameters, Meaning and Response.Write the same, if you do not call the function, the client will always be in a waiting state;
Creating an HTTP ClientHTTP provides two functions ==http.request== and ==http.get==, as the client initiates a request to the HTTP server;
1. Http.request (options[, callback])const postData = querystring.stringify({ ‘msg‘ : ‘Hello World!‘});const options = { hostname: ‘www.google.com‘, port: 80, path: ‘/upload‘, method: ‘POST‘, headers: { ‘Content-Type‘: ‘application/x-www-form-urlencoded‘, ‘Content-Length‘: Buffer.byteLength(postData) }};const req = http.request(options, (res) => { console.log(`状态码: ${res.statusCode}`); console.log(`响应头: ${JSON.stringify(res.headers)}`); res.setEncoding(‘utf8‘); res.on(‘data‘, (chunk) => { console.log(`响应主体: ${chunk}`); }); res.on(‘end‘, () => { console.log(‘响应中已无数据。‘); });});req.on(‘error‘, (e) => { console.error(`请求遇到问题: ${e.message}`);});// 写入数据到请求主体req.write(postData);req.end();
Note that Req.end () is called in the example. Using Http.request () must always call Req.end () to indicate the end of the request, even if no data is written to the request body.
If any errors (DNS resolution errors, TCP-level errors, or actual HTTP parsing errors) are encountered during the request, the ' error ' event is triggered in the returned request object. For all ' error ' events, an error is thrown if no listener is registered.
Here are a few special request headers to be aware of.
-
Send ' connection:keep-alive ' notifies node. js that the connection to the server should persist until the next request.
-
Sending the ' content-length ' request header disables the default block encoding. The
-
Send ' Expect ' request header immediately sends the request header. Normally, when sending ' expect:100-continue ', the time-out and the listener for the continue event need to be set. See RFC2616 Chapter 8.2.3. The
-
Send Authorization request header overrides the AUTH option to calculate Basic authentication.
2. Http.get (options[, callback]) the object is created inside the HTTP server. As a second argument, the incoming ' request ' event
-
Receives the same settings as Http.request (). Method is always set to get, ignoring properties inherited from the prototype
- return:
http.get(‘http://nodejs.org/dist/index.json‘, (res) => { const { statusCode } = res; const contentType = res.headers[‘content-type‘]; let error; if (statusCode !== 200) { error = new Error(‘请求失败。\n‘ + `状态码: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error(‘无效的 content-type.\n‘ + `期望 application/json 但获取的是 ${contentType}`); } if (error) { console.error(error.message); // 消耗响应数据以释放内存 res.resume(); return; } res.setEncoding(‘utf8‘); let rawData = ‘‘; res.on(‘data‘, (chunk) => { rawData += chunk; }); res.on(‘end‘, () => { try { const parsedData = JSON.parse(rawData); console.log(parsedData); } catch (e) { console.error(e.message); } });}).on(‘error‘, (e) => { console.error(`错误: ${e.message}`);});
3. http. ClientrequestThe object is created and returned inside the Http.request (). It represents a regular processing request whose request header has entered the queue. The request header can still be modified using SetHeader (name, value), GetHeader (name), and Removeheader (name). The actual request header is sent with the first block of data or when Request.end () is called.
Const HTTP = require (' http '); const NET = require (' net '); Const URL = require (' URL ');//Create an HTTP proxy server const proxy = http.cr Eateserver ((req, res) = {Res.writehead ($, {' Content-type ': ' Text/plain '}); Res.end (' okay ');}); Proxy.on (' Connect ', (req, cltsocket, head) = {//connect to a server const SRVURL = Url.parse (' Http://${req.url} '); Const Srvsocket = Net.connect (Srvurl.port, Srvurl.hostname, () = {cltsocket.write (' http/1.1 Connection establi shed\r\n ' + ' proxy-agent:node.js-proxy\r\n ' + ' \ r \ n '); Srvsocket.write (head); Srvsocket.pipe (Cltsocket); Cltsocket.pipe (Srvsocket); });});/ /proxy Server is running Proxy.listen (1337, ' 127.0.0.1 ', () = {//send a request to proxy server Const options = {port:1337, hostname: ' 127 .0.0.1 ', method: ' CONNECT ', Path: ' www.google.com:80 '}; Const REQ = http.request (options); Req.end (); Req.on (' Connect ', (res, socket, head) = {Console.log (' Connected! ‘); Send a request via Proxy server Socket.write (' Get/http/1.1\r\n ' + ' host:www.google.com:80\r\n ' + ' connection:close\r\n ' + ' \ r\n '); Socket.on (' Data ', (chunk) = {Console.log (chunk.tostring ()); }); Socket.on (' End ', () = {proxy.close (); }); });});
4. http. AgentResponsible for managing the continuity and reuse of connections for HTTP clients. It maintains a queue of waiting requests for a given host and port, and repeats a single socket connection for each request until the queue is empty, at which point the socket is destroyed in a connection pool waiting to be reused by the same host and port request. Whether it is destroyed or put into the connection pool depends on the keepAlive option.
http.get(options, (res) => { // 处理事情}).on(‘socket‘, (socket) => { socket.emit(‘agentRemove‘);});
When the socket triggers a ' close ' event or ' agentremove ' event, it is removed from the proxy. When you intend to keep an HTTP request open for a long time and do not want it to remain in the agent, you can handle it as above
The core module of "Node" node---HTTP module, HTTP server and client