本文共 8524 字,大约阅读时间需要 28 分钟。
node http模块
The HTTP core module is a key module to Node networking.
HTTP核心模块是Node联网的关键模块。
It can be included using
可以使用
const http = require('http')
The module provides some properties and methods, and some classes.
该模块提供了一些属性和方法以及一些类。
http.METHODS
(http.METHODS
)This property lists all the HTTP methods supported:
此属性列出了所有受支持的HTTP方法:
> require('http').METHODS[ 'ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LINK', 'LOCK', 'M-SEARCH', 'MERGE', 'MKACTIVITY', 'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS', 'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REBIND', 'REPORT', 'SEARCH', 'SUBSCRIBE', 'TRACE', 'UNBIND', 'UNLINK', 'UNLOCK', 'UNSUBSCRIBE' ]
http.STATUS_CODES
(http.STATUS_CODES
)This property lists all the HTTP status codes and their description:
此属性列出了所有HTTP状态代码及其描述:
> require('http').STATUS_CODES{ '100': 'Continue', '101': 'Switching Protocols', '102': 'Processing', '200': 'OK', '201': 'Created', '202': 'Accepted', '203': 'Non-Authoritative Information', '204': 'No Content', '205': 'Reset Content', '206': 'Partial Content', '207': 'Multi-Status', '208': 'Already Reported', '226': 'IM Used', '300': 'Multiple Choices', '301': 'Moved Permanently', '302': 'Found', '303': 'See Other', '304': 'Not Modified', '305': 'Use Proxy', '307': 'Temporary Redirect', '308': 'Permanent 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 Timeout', '409': 'Conflict', '410': 'Gone', '411': 'Length Required', '412': 'Precondition Failed', '413': 'Payload Too Large', '414': 'URI Too Long', '415': 'Unsupported Media Type', '416': 'Range Not Satisfiable', '417': 'Expectation Failed', '418': 'I\'m a teapot', '421': 'Misdirected Request', '422': 'Unprocessable Entity', '423': 'Locked', '424': 'Failed Dependency', '425': 'Unordered Collection', '426': 'Upgrade Required', '428': 'Precondition Required', '429': 'Too Many Requests', '431': 'Request Header Fields Too Large', '451': 'Unavailable For Legal Reasons', '500': 'Internal Server Error', '501': 'Not Implemented', '502': 'Bad Gateway', '503': 'Service Unavailable', '504': 'Gateway Timeout', '505': 'HTTP Version Not Supported', '506': 'Variant Also Negotiates', '507': 'Insufficient Storage', '508': 'Loop Detected', '509': 'Bandwidth Limit Exceeded', '510': 'Not Extended', '511': 'Network Authentication Required' }
http.globalAgent
(http.globalAgent
)Points to the global instance of the Agent object, which is an instance of the http.Agent
class.
指向Agent对象的全局实例,该实例是http.Agent
类的实例。
It’s used to manage connections persistance and reuse for HTTP clients, and it’s a key component of Node HTTP networking.
它用于管理HTTP客户端的连接持久性和重用,它是Node HTTP网络的关键组成部分。
More in the http.Agent
class description later on.
稍后会在http.Agent
类说明中提供更多信息。
http.createServer()
(http.createServer()
)Return a new instance of the http.Server
class.
返回http.Server
类的新实例。
Usage:
用法:
const server = http.createServer((req, res) => { //handle every single request with this callback})
http.request()
(http.request()
)Makes an HTTP request to a server, creating an instance of the http.ClientRequest
class.
向服务器发出HTTP请求,并创建http.ClientRequest
类的实例。
http.get()
(http.get()
)Similar to http.request()
, but automatically sets the HTTP method to GET, and calls req.end()
automatically.
与http.request()
类似,但会自动将HTTP方法设置为GET,并自动调用req.end()
。
The HTTP module provides 5 classes:
HTTP模块提供5个类:
http.Agent
http.Agent
http.ClientRequest
http.ClientRequest
http.Server
http.Server
http.ServerResponse
http.ServerResponse
http.IncomingMessage
http.IncomingMessage
http.Agent
(http.Agent
)Node creates a global instance of the http.Agent
class to manage connections persistance and reuse for HTTP clients, a key component of Node HTTP networking.
Node创建http.Agent
类的全局实例,以管理HTTP客户端(Node HTTP网络的关键组件)的连接持久性和重用。
This object makes sure that every request made to a server is queued and a single socket is reused.
该对象确保对服务器的每个请求都排队,并且单个套接字被重用。
It also maintains a pool of sockets. This is key for performance reasons.
它还维护一个套接字池。 出于性能原因,这是关键。
http.ClientRequest
(http.ClientRequest
)An http.ClientRequest
object is created when http.request()
or http.get()
is called.
当http.request()
或http.get()
时,将创建一个http.ClientRequest
对象。
When a response is received, the response
event is called with the response, with an http.IncomingMessage
instance as argument.
接收到响应后,将使用http.IncomingMessage
实例作为参数来调用response
事件和响应。
The returned data of a response can be read in 2 ways:
可以通过两种方式读取响应的返回数据:
you can call the response.read()
method
您可以调用response.read()
方法
in the response
event handler you can setup an event listener for the data
event, so you can listen for the data streamed into.
在response
事件处理程序中,您可以为data
事件设置事件侦听器,以便可以侦听流入的数据。
http.Server
(http.Server
)This class is commonly instantiated and returned when creating a new server using http.createServer()
.
使用http.createServer()
创建新服务器时,通常会实例化并返回http.createServer()
。
Once you have a server object, you have access to its methods:
拥有服务器对象后,就可以访问其方法:
close()
stops the server from accepting new connections
close()
阻止服务器接受新连接
listen()
starts the HTTP server and listens for connections
listen()
启动HTTP服务器并侦听连接
http.ServerResponse
(http.ServerResponse
)Created by an http.Server
and passed as the second parameter to the request
event it fires.
由http.Server
创建,并作为第二个参数传递给它触发的request
事件。
Commonly known and used in code as res
:
众所周知并在代码中用作res
:
const server = http.createServer((req, res) => { //res is an http.ServerResponse object})
The method you’ll always call in the handler is end()
, which closes the response, the message is complete and the server can send it to the client. It must be called on each response.
您将始终在处理程序中调用的方法是end()
,它将关闭响应,消息已完成,服务器可以将其发送给客户端。 必须在每个响应上调用它。
These methods are used to interact with HTTP headers:
这些方法用于与HTTP标头进行交互:
getHeaderNames()
get the list of the names of the HTTP headers already set
getHeaderNames()
获取已设置的HTTP标头名称的列表
getHeaders()
get a copy of the HTTP headers already set
getHeaders()
获取已设置的HTTP标头的副本
setHeader('headername', value)
sets an HTTP header value
setHeader('headername', value)
设置HTTP标头值
getHeader('headername')
gets an HTTP header already set
getHeader('headername')
获取已设置的HTTP标头
removeHeader('headername')
removes an HTTP header already set
removeHeader('headername')
删除已设置的HTTP标头
hasHeader('headername')
return true if the response has that header set
如果响应已设置该标头,则hasHeader('headername')
返回true
headersSent()
return true if the headers have already been sent to the client
如果标头已经发送到客户端,则headersSent()
返回true
After processing the headers you can send them to the client by calling response.writeHead()
, which accepts the statusCode as the first parameter, the optional status message, and the headers object.
处理头之后,您可以通过调用response.writeHead()
将它们发送到客户端,该方法接受statusCode作为第一个参数,可选的状态消息和头对象。
To send data to the client in the response body, you use write()
. It will send buffered data to the HTTP response stream.
要将数据发送到响应正文中的客户端,请使用write()
。 它将缓冲的数据发送到HTTP响应流。
If the headers were not sent yet using response.writeHead()
, it will send the headers first, with the status code and message that’s set in the request, which you can edit by setting the statusCode
and statusMessage
properties values:
如果尚未使用response.writeHead()
发送标头,它将首先发送标头,其中包含在请求中设置的状态代码和消息,您可以通过设置statusCode
和statusMessage
属性值进行编辑:
response.statusCode = 500response.statusMessage = 'Internal Server Error'
http.IncomingMessage
(http.IncomingMessage
)An http.IncomingMessage
object is created by:
通过http.IncomingMessage
方式创建http.IncomingMessage
对象:
http.Server
when listening to the request
event
侦听request
事件时的http.Server
http.ClientRequest
when listening to the response
event
侦听response
事件时的http.ClientRequest
It can be used to access the response:
它可以用来访问响应:
status using its statusCode
and statusMessage
methods
状态使用其statusCode
和statusMessage
方法
headers using its headers
method or rawHeaders
标头使用其headers
方法或rawHeaders
HTTP method using its method
method
使用其HTTP方法method
方法
HTTP version using the httpVersion
method
使用httpVersion
方法的HTTP版本
URL using the url
method
使用url
方法的url
underlying socket using the socket
method
使用socket
方法的基础套接字
The data is accessed using streams, since http.IncomingMessage
implements the Readable Stream interface.
由于http.IncomingMessage
实现了Readable Stream接口,因此使用流访问数据。
翻译自:
node http模块
转载地址:http://nmqgb.baihongyu.com/