Home > Web Front-end > JS Tutorial > body text

NodeJS study notes Http module_node.js

WBOY
Release: 2016-05-16 16:20:20
Original
1317 people have browsed it

1, opening analysis

First of all, everyone should be familiar with the concept of "Http". It is not based on a specific language. It is a general application layer protocol. Different languages ​​have different implementation details, but they remain the same and the ideas are the same.

As a host operating environment, NodeJS uses JavaScript as the host language. It also has its own set of standards for implementation. In this article, we will learn about the "Http module" together. But as a premise,

I hope you can read the API provided by the official website first and have a pre-understanding, which will be much more convenient. The following is an overview of the API of the Http part:

Copy code The code is as follows:

HTTP
    http.STATUS_CODES
    http.createServer([requestListener])
    http.createClient([port], [host])
    Class: http.Server
    事件 : 'request'
    事件: 'connection'
    事件: 'close'
    Event: 'checkContinue'
    事件: 'connect'
    Event: 'upgrade'
    Event: 'clientError'
    server.listen(port, [hostname], [backlog], [callback])
    server.listen(path, [callback])
    server.listen(handle, [callback])
    server.close([callback])
    server.maxHeadersCount
    server.setTimeout(msecs, callback)
    server.timeout
    Class: http.ServerResponse
        事件: 'close'
        response.writeContinue()
        response.writeHead(statusCode, [reasonPhrase], [headers])
        response.setTimeout(msecs, callback)
        response.statusCode
        response.setHeader(name, value)
        response.headersSent
        response.sendDate
        response.getHeader(name)
        response.removeHeader(name)
        response.write(chunk, [encoding])
        response.addTrailers(headers)
        response.end([data], [encoding])
        http.request(options, callback)
        http.get(options, callback)
    Class: http.Agent
        new Agent([options])
        agent.maxSockets
        agent.maxFreeSockets
        agent.sockets
        agent.freeSockets
        agent.requests
        agent.destroy()
        agent.getName(options)
        http.globalAgent
    Class: http.ClientRequest
        Event 'response'
        Event: 'socket'
        事件: 'connect'
        Event: 'upgrade'
        Event: 'continue'
        request.write(chunk, [encoding])
        request.end([data], [encoding])
        request.abort()
        request.setTimeout(timeout, [callback])
        request.setNoDelay([noDelay])
        request.setSocketKeepAlive([enable], [initialDelay])
    http.IncomingMessage
        事件: 'close'
        message.httpVersion
        message.headers
        message.rawHeaders
        message.trailers
        message.rawTrailers
        message.setTimeout(msecs, callback)
        message.method
        message.url
        message.statusCode
        message.socket

让我们先从一个简单例子开始,创建一个叫server.js的文件,并写入以下代码:

复制代码 代码如下:

var http = require('http') ;
var server = http.createServer(function(req,res){
res.writeHeader(200,{
'Content-Type' : 'text/plain;charset=utf-8' // Add charset=utf-8
}) ;
res.end("Hello, Big Bear!") ;
}) ;
server.listen(8888) ;
console.log("http server running on port 8888 ...") ;

(node ​​server.js) The following are the results:

2. Detailed analysis examples

Look at this small example in detail:

(Line 1): Introduce the "http" module that comes with NodeJS through "require" and assign it to the http variable.

(2 lines): Call the function provided by the http module: "createServer". This function returns a new web server object.

 The parameter "requestListener" is a function that will automatically be added to the listening queue of the "request" event.

When a request comes, Event-Loop will put the Listener callback function into the execution queue, and all the code in the node will be taken out of the execution queue one by one for execution.

These executions are all performed on the working thread (Event Loop itself can be considered to be in an independent thread. We generally do not mention this thread, but call node a single-threaded execution environment),

All callbacks are run on a worker thread.

Let’s take a look at the callback function "requestListener" again, which provides two parameters (request, response),

Fired every time a request is received. Note that each connection may have multiple requests (in a keep-alive connection).

"request" is an instance of http.IncomingMessage. "response" is an instance of http.ServerResponse.

An http request object is a readable stream, and an http response object is a writable stream.

An "IncomingMessage" object is created by http.Server or http.ClientRequest,

And passed as the first parameter to the "request" and "response" events respectively.

It can also be used to access response status, headers and data.

 It implements the "Stream" interface and the following additional events, methods and properties. (Refer to API for details).

(3 lines): "writeHeader", use the "response.writeHead()" function to send an Http status 200 and the content-type of the Http header.

Reply the response header to the request. "statusCode" is a three-digit HTTP status code, such as 404. The last parameter, "headers", is the content of the response headers.

Give me an example:

Copy code The code is as follows:

var body = 'hello world' ;
response.writeHead(200, {
‘Content-Length’: body.length,
'Content-Type': 'text/plain'
}) ;

Note: Content-Length is calculated in bytes, not characters.

The reason for the previous example is that the string "Hello World!" only contains single-byte characters.

If the body contains multi-byte encoded characters, you should use Buffer.byteLength() to determine the number of bytes of the string in the case of multi-byte character encoding.

It should be further explained that Node does not check whether the Content-Lenth attribute matches the transmitted body length.

statusCode is a three-digit HTTP status code, for example: "404". What I want to talk about here is "http.STATUS_CODES", which contains the collection and short description of all standard "Http" response status codes.

The following is the source code reference:

Copy code The code is as follows:

var STATUS_CODES = exports.STATUS_CODES = {
  100 : 'Continue',
  101 : 'Switching Protocols',
  102 : 'Processing',                 // RFC 2518, obsoleted by RFC 4918
  200 : 'OK',
  201 : 'Created',
  202 : 'Accepted',
  203 : 'Non-Authoritative Information',
  204 : 'No Content',
  205 : 'Reset Content',
  206 : 'Partial Content',
  207 : 'Multi-Status',               // RFC 4918
  300 : 'Multiple Choices',
  301 : 'Moved Permanently',
  302 : 'Moved Temporarily',
  303 : 'See Other',
  304 : 'Not Modified',
  305 : 'Use Proxy',
  307 : 'Temporary Redirect',
  400 : 'Bad Request',
  401 : 'Unauthorized',
  402 : 'Payment Required',
  403 : 'Forbidden',
  404 : 'Not Found',
  405 : 'Method Not Allowed',
  406 : 'Not Acceptable',
  407 : 'Proxy Authentication Required',
  408 : 'Request Time-out',
  409 : 'Conflict',
  410 : 'Gone',
  411 : 'Length Required',
  412 : 'Precondition Failed',
  413 : 'Request Entity Too Large',
  414 : 'Request-URI Too Large',
  415 : 'Unsupported Media Type',
  416 : 'Requested Range Not Satisfiable',
  417 : 'Expectation Failed',
  418 : 'I'm a teapot',              // RFC 2324
  422 : 'Unprocessable Entity',       // RFC 4918
  423 : 'Locked',                     // RFC 4918
  424 : 'Failed Dependency',          // RFC 4918
  425 : 'Unordered Collection',       // RFC 4918
  426 : 'Upgrade Required',           // RFC 2817
  500 : 'Internal Server Error',
  501 : 'Not Implemented',
  502 : 'Bad Gateway',
  503 : 'Service Unavailable',
  504 : 'Gateway Time-out',
  505 : 'HTTP Version not supported',
  506 : 'Variant Also Negotiates',    // RFC 2295
  507 : 'Insufficient Storage',       // RFC 4918
  509 : 'Bandwidth Limit Exceeded',
  510 : 'Not Extended'                // RFC 2774
};

节选自,Nodejs源码 ”http.js“ 143行开始。

其实从客户端应答结果也不难看出:

 

(6行):”response.end“------当所有的响应报头和报文被发送完成时这个方法将信号发送给服务器。服务器会认为这个消息完成了。

  每次响应完成之后必须调用该方法。如果指定了参数 “data” ,就相当于先调用  “response.write(data, encoding) ” 之后再调用 “response.end()” 。

(8行):”server.listen(8888)“ ------ 服务器用指定的句柄接受连接,绑定在特定的端口。

以上就是一个比较详细的分析过程,希望有助于加深理解,代码虽然不多,但是重在理解一些细节机制,以便日后高效的开发NodeJS应用。

三,实例

除了可以使用"request"对象访问请求头数据外,还能把"request"对象当作一个只读数据流来访问请求体数据。

这是一个"POST"请求的例子:

复制代码 代码如下:

http.createServer(function (request, response) {
var body = [];
console.log(request.method) ;
console.log(request.headers) ;
Request.on('data', function (chunk) {
            body.push(chunk);
}) ;
Request.on('end', function () {
​​​​body = Buffer.concat(body);
console.log(body.toString()) ;
});
}).listen(8888) ;

The following is a complete "Http" request data content.

Copy code The code is as follows:

POST/HTTP/1.1
User-Agent: curl/7.26.0
Host: localhost
Accept: */*
Content-Length: 11
Content-Type: application/x-www-form-urlencoded
Hello World

Four, summary

(1), understand the concept of "Http".
(2), be proficient in using "Http" related APIs.
(3) Pay attention to the details, such as the processing details between "POST, GET".
(4), understanding of "requestListener".
(5), emphasizes a concept: an http request object is a readable stream, and an http response object is a writable stream.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template