The core module of "Node" node---HTTP module, HTTP server and client

Source: Internet
Author: User
Tags emit response code

HTTP Server and Client

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 C + + section of the node. JS Downlevel While the interface is packaged in JavaScript, both performance and simplicity, Http.request is an HTTP client tool for initiating requests to the HTTP service;

Create HTTP server 1. Http.createserver ()
//服务器实例var httpServer = require("http")httpServer.createServer(function(req,res){        res.writeHead(200,{"Content-Type":"text/html"});         res.write("

Http.createserver creates an Http.server instance that takes a function as an HTTP request handler, which takes two parameters, namely the Request object (req) and the Response object (RES), and the Res explicitly writes back the response code 200 in the function body. (indicates a successful request), specifying the response header as "Content-type": "text/html", and then writing the response body through res.end () to end and send, and finally call the Listen function, start the server and listen on port 2333

2. http. Server class

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

    • Connection: When the TCP link is established, the event is triggered, providing a parameter socket, which is net. 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 link in keep-alive mode
wsServer.on(‘connection‘,function(sock){ sock.on(‘a‘,function(num1,num2){   console.log(`接到了浏览器发送的数据:${num1}`) }) setInterval(function(){   sock.emit(‘ttt‘,Math.random()) },500)})
    • Close: When the server shuts down, the event is triggered, not when the user is disconnected, and so on.
    • Request: Triggered each time a request is received.
var server = new http.Server(); server.on("request", function (req, res) {   res.writeHead(200, { "Content-Type": "text/html" });    res.write("
3. http. Serverresponse

http. 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 Client

HTTP 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. Clientrequest

The 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.

    • Connect Event
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. Agent

Responsible 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

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.