httpclient;

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
您的访问请求被拒绝 403 Forbidden - ITeye技术社区
您的访问请求被拒绝
亲爱的会员,您的IP地址所在网段被ITeye拒绝服务,这可能是以下两种情况导致:
一、您所在的网段内有网络爬虫大量抓取ITeye网页,为保证其他人流畅的访问ITeye,该网段被ITeye拒绝
二、您通过某个代理服务器访问ITeye网站,该代理服务器被网络爬虫利用,大量抓取ITeye网页
请您点击按钮解除封锁&HTTP Node.js v5.11.0 Manual & Documentation
Node.js v5.11.0 Documentation
Table of Contents
Stability: 2 - StableTo use the HTTP server and client one must require(&#39;http&#39;).
The HTTP interfaces in Node.js are designed to support many features
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
careful to never buffer entire requests or responses--the
user is able to stream data.
HTTP message headers are represented by an object like this:
{ &#39;content-length&#39;: &#39;123&#39;,
&#39;content-type&#39;: &#39;text/plain&#39;,
&#39;connection&#39;: &#39;keep-alive&#39;,
&#39;host&#39;: &#&#39;,
&#39;accept&#39;: &#39;*/*&#39; }
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, Node.js&#39;s
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.
for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders
property, which is an array of [key, value, key2, value2, ...].
example, the previous message header object might have a rawHeaders
list like the following:
[ &#39;ConTent-Length&#39;, &#39;;,
&#39;content-LENGTH&#39;, &#39;123&#39;,
&#39;content-type&#39;, &#39;text/plain&#39;,
&#39;CONNECTION&#39;, &#39;keep-alive&#39;,
&#39;Host&#39;, &#&#39;,
&#39;accepT&#39;, &#39;*/*&#39; ]
Class: http.Agent
The HTTP Agent is used for pooling sockets used in HTTP client
The HTTP Agent also defaults client requests to using
Connection:keep-alive. If no pending HTTP requests are waiting on a
socket to become free the socket is closed. This means that Node.js&#39;s
pool has the benefit of keep-alive when under load but still does not
require developers to manually close the HTTP clients using
KeepAlive.
If you opt into using HTTP KeepAlive, you can create an Agent object
with that flag set to true.
(See the .)
Then, the Agent will keep unused sockets in a pool for later use.
will be explicitly marked so as to not keep the Node.js process running.
However, it is still a good idea to explicitly
agents when they are no longer in use, so that the Sockets will be shut
Sockets are removed from the agent&#39;s pool when the socket emits either
a &#39;close&#39; event or a special &#39;agentRemove&#39; event. This means that if
you intend to keep one HTTP request open for a long time and don&#39;t
want it to stay in the pool you can do something along the lines of:
http.get(options, (res) =& {
// Do stuff
}).on(&#39;socket&#39;, (socket) =& {
socket.emit(&#39;agentRemove&#39;);
Alternatively, you could just opt out of pooling entirely using
agent:false:
http.get({
hostname: &#39;localhost&#39;,
path: &#39;/&#39;,
agent: false
// create a new agent just for this one request
}, (res) =& {
// Do stuff with response
new Agent([options])
Set of configurable options to set on the agent.
Can have the following fields:
Keep sockets around in a pool to be used by
other requests in the future. Default = false
keepAliveMsecs &Integer& When using HTTP KeepAlive, how often
to send TCP KeepAlive packets over sockets being kept alive.
Default = 1000.
Only relevant if keepAlive is set to true.
maxSockets
Maximum number of sockets to allow per
Default = Infinity.
maxFreeSockets
Maximum number of sockets to leave open
in a free state.
Only relevant if keepAlive is set to true.
Default = 256.
The default
that is used by
of these values set to their respective defaults.
To configure any of them, you must create your own
const http = require(&#39;http&#39;);
var keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveA
http.request(options, onResponseCallback);
agent.createConnection(options[, callback])
Produces a socket/stream to be used for HTTP requests.
By default, this function is the same as . However,
custom Agents may override this method in case greater flexibility is desired.
A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to callback.
callback has a signature of (err, stream).
agent.destroy()
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this.
However, if you are using an
agent with KeepAlive enabled, then it is best to explicitly shut down
the agent when you know that it will no longer be used.
Otherwise,
sockets may hang open for quite a long time before the server
terminates them.
agent.freeSockets
An object which contains arrays of sockets currently awaiting use by
the Agent when HTTP KeepAlive is used.
Do not modify.
agent.getName(options)
Get a unique name for a set of request options, to determine whether a
connection can be reused.
In the http agent, this returns
host:port:localAddress.
In the https agent, the name includes the
CA, cert, ciphers, and other HTTPS/TLS-specific options that determine
socket reusability.
host: A domain name or IP address of the server to issue the request to.
port: Port of remote server.
localAddress: Local interface to bind for network connections when issuing
the request.
agent.maxFreeSockets
By default set to 256.
For Agents supporting HTTP KeepAlive, this
sets the maximum number of sockets that will be left open in the free
agent.maxSockets
By default set to Infinity. Determines how many concurrent sockets the agent
can have open per origin. Origin is either a &#39;host:port&#39; or
&#39;host:port:localAddress&#39; combination.
agent.requests
An object which contains queues of requests that have not yet been assigned to
sockets. Do not modify.
agent.sockets
An object which contains arrays of sockets currently in use by the
Do not modify.
Class: http.ClientRequest
This object is created internally and returned from .
represents an in-progress request whose header has already been queued.
header is still mutable using the setHeader(name, value), getHeader(name),
removeHeader(name) API.
The actual header will be sent along with the first
data chunk or when closing the connection.
To get the response, add a listener for &#39;response&#39; to the request object.
&#39;response&#39; will be emitted from the request object when the response
headers have been received.
The &#39;response&#39; event is executed with one
argument which is an instance of .
During the &#39;response&#39; event, one can add listeners to the
particularly to listen for the &#39;data&#39; event.
If no &#39;response&#39; handler is added, then the response will be
entirely discarded.
However, if you add a &#39;response&#39; event handler,
then you must consume the data from the response object, either by
calling response.read() whenever there is a &#39;readable&#39; event, or
by adding a &#39;data&#39; handler, or by calling the .resume() method.
Until the data is consumed, the &#39;end&#39; event will not fire.
Also, until
the data is read it will consume memory that can eventually lead to a
&#39;process out of memory&#39; error.
Note: Node.js does not check whether Content-Length and the length of the body
which has been transmitted are equal or not.
The request implements the
interface. This is an
with the following events:
Event: &#39;abort&#39;
function () { }
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to abort().
Event: &#39;checkExpectation&#39;
function (request, response) { }
Emitted each time a request with an http Expect header is received, where the
value is not 100-continue. If this event isn&#39;t listened for, the server will
automatically respond with a 417 Expectation Failed as appropriate.
Note that when this event is emitted and handled, the request event will
not be emitted.
Event: &#39;connect&#39;
function (response, socket, head) { }
Emitted each time a server responds to a request with a CONNECT method. If this
event isn&#39;t being listened for, clients receiving a CONNECT method will have
their connections closed.
A client server pair that show you how to listen for the &#39;connect&#39; event.
const http = require(&#39;http&#39;);
const net = require(&#39;net&#39;);
const url = require(&#39;url&#39;);
// Create an HTTP tunneling proxy
var proxy = http.createServer( (req, res) =& {
res.writeHead(200, {&#39;Content-Type&#39;: &#39;text/plain&#39;});
res.end(&#39;okay&#39;);
proxy.on(&#39;connect&#39;, (req, cltSocket, head) =& {
// connect to an origin server
var srvUrl = url.parse(`http://${req.url}`);
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () =& {
cltSocket.write(&#39;HTTP/1.1 200 Connection Established\r\n&#39; +
&#39;Proxy-agent: Node.js-Proxy\r\n&#39; +
&#39;\r\n&#39;);
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
// now that proxy is running
proxy.listen(1337, &#39;127.0.0.1&#39;, () =& {
// make a request to a tunneling proxy
var options = {
port: 1337,
hostname: &#39;127.0.0.1&#39;,
method: &#39;CONNECT&#39;,
path: &#39;:80&#39;
var req = http.request(options);
req.end();
req.on(&#39;connect&#39;, (res, socket, head) =& {
console.log(&#39;got connected!&#39;);
// make a request over an HTTP tunnel
socket.write(&#39;GET / HTTP/1.1\r\n&#39; +
&#39;Host: :80\r\n&#39; +
&#39;Connection: close\r\n&#39; +
&#39;\r\n&#39;);
socket.on(&#39;data&#39;, (chunk) =& {
console.log(chunk.toString());
socket.on(&#39;end&#39;, () =& {
proxy.close();
Event: &#39;continue&#39;
function () { }
Emitted when the server sends a &#39;100 Continue&#39; HTTP response, usually because
the request contained &#39;Expect: 100-continue&#39;. This is an instruction that
the client should send the request body.
Event: &#39;response&#39;
function (response) { }
Emitted when a response is received to this request. This event is emitted only
once. The response argument will be an instance of .
Event: &#39;socket&#39;
function (socket) { }
Emitted after a socket is assigned to this request.
Event: &#39;upgrade&#39;
function (response, socket, head) { }
Emitted each time a server responds to a request with an upgrade. If this
event isn&#39;t being listened for, clients receiving an upgrade header will have
their connections closed.
A client server pair that show you how to listen for the &#39;upgrade&#39; event.
const http = require(&#39;http&#39;);
// Create an HTTP server
var srv = http.createServer( (req, res) =& {
res.writeHead(200, {&#39;Content-Type&#39;: &#39;text/plain&#39;});
res.end(&#39;okay&#39;);
srv.on(&#39;upgrade&#39;, (req, socket, head) =& {
socket.write(&#39;HTTP/1.1 101 Web Socket Protocol Handshake\r\n&#39; +
&#39;Upgrade: WebSocket\r\n&#39; +
&#39;Connection: Upgrade\r\n&#39; +
&#39;\r\n&#39;);
socket.pipe(socket); // echo back
// now that server is running
srv.listen(1337, &#39;127.0.0.1&#39;, () =& {
// make a request
var options = {
port: 1337,
hostname: &#39;127.0.0.1&#39;,
headers: {
&#39;Connection&#39;: &#39;Upgrade&#39;,
&#39;Upgrade&#39;: &#39;websocket&#39;
var req = http.request(options);
req.end();
req.on(&#39;upgrade&#39;, (res, socket, upgradeHead) =& {
console.log(&#39;got upgraded!&#39;);
socket.end();
process.exit(0);
request.abort()
Marks the request as aborting. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.
request.end([data][, encoding][, callback])
Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating &#39;0\r\n\r\n&#39;.
If data is specified, it is equivalent to calling
followed by request.end(callback).
If callback is specified, it will be called when the request stream
is finished.
request.flushHeaders()
Flush the request headers.
For efficiency reasons, Node.js normally buffers the request headers until you
call request.end() or write the first chunk of request data.
It then tries
hard to pack the request headers and data into a single TCP packet.
That&#39;s usually what you want (it saves a TCP round-trip) but not when the first
data isn&#39;t sent until possibly much later.
request.flushHeaders() lets you bypass
the optimization and kickstart the request.
request.setNoDelay([noDelay])
Once a socket is assigned to this request and is connected
will be called.
request.setSocketKeepAlive([enable][, initialDelay])
Once a socket is assigned to this request and is connected
will be called.
request.setTimeout(timeout[, callback])
Once a socket is assigned to this request and is connected
will be called.
Milliseconds before a request is considered to be timed out.
Optional function to be called when a timeout occurs. Same as binding to the timeout event.
request.write(chunk[, encoding][, callback])
Sends a chunk of the body.
By calling this method
many times, the user can stream a request body to a
server--in that case it is suggested to use the
[&#39;Transfer-Encoding&#39;, &#39;chunked&#39;] header line when
creating the request.
The chunk argument should be a
or a string.
The encoding argument is optional and only applies when chunk is a string.
Defaults to &#39;utf8&#39;.
The callback argument is optional and will be called when this chunk of data
is flushed.
Returns request.
Class: http.Server
This class inherits from
and has the following additional events:
Event: &#39;checkContinue&#39;
function (request, response) { }
Emitted each time a request with an http Expect: 100-continue is received.
If this event isn&#39;t listened for, the server will automatically respond
with a 100 Continue as appropriate.
Handling this event involves calling
if the client
should continue to send the request body, or generating an appropriate HTTP
response (e.g., 400 Bad Request) if the client should not continue to send the
request body.
Note that when this event is emitted and handled, the &#39;request&#39; event will
not be emitted.
Event: &#39;clientError&#39;
function (exception, socket) { }
If a client connection emits an &#39;error&#39; event, it will be forwarded here.
socket is the
object that the error originated from.
Event: &#39;close&#39;
function () { }
Emitted when the server closes.
Event: &#39;connect&#39;
function (request, socket, head) { }
Emitted each time a client requests a http CONNECT method. If this event isn&#39;t
listened for, then clients requesting a CONNECT method will have their
connections closed.
request is the arguments for the http request, as it is in the request
socket is the network socket between the server and client.
head is an instance of Buffer, the first packet of the tunneling stream,
this may be empty.
After this event is emitted, the request&#39;s socket will not have a &#39;data&#39;
event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket.
Event: &#39;connection&#39;
function (socket) { }
When a new TCP stream is established. socket is an object of type
. Usually users will not want to access this event. In
particular, the socket will not emit &#39;readable&#39; events because of how
the protocol parser attaches to the socket. The socket can also be
accessed at request.connection.
Event: &#39;request&#39;
function (request, response) { }
Emitted each time there is a request. Note that there may be multiple requests
per connection (in the case of keep-alive connections).
request is an instance of
and response is
an instance of .
Event: &#39;upgrade&#39;
function (request, socket, head) { }
Emitted each time a client requests a http upgrade. If this event isn&#39;t
listened for, then clients requesting an upgrade will have their connections
request is the arguments for the http request, as it is in the request
socket is the network socket between the server and client.
head is an instance of Buffer, the first packet of the upgraded stream,
this may be empty.
After this event is emitted, the request&#39;s socket will not have a &#39;data&#39;
event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket.
server.close([callback])
Stops the server from accepting new connections.
server.listen(handle[, callback])
The handle object can be set to either a server or socket (anything
with an underlying _handle member), or a {fd: &n&} object.
This will cause the server to accept connections on the specified
handle, but it is presumed that the file descriptor or handle has
already been bound to a port or domain socket.
Listening on a file descriptor is not supported on Windows.
This function is asynchronous. The last parameter callback will be added as
a listener for the &#39;listening&#39; event. See also .
Returns server.
server.listen(path[, callback])
Start a UNIX socket server listening for connections on the given path.
This function is asynchronous. The last parameter callback will be added as
a listener for the &#39;listening&#39; event.
See also .
server.listen(port[, hostname][, backlog][, callback])
Begin accepting connections on the specified port and hostname. If the
hostname is omitted, the server will accept connections on any IPv6 address
(::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. A
port value of zero will assign a random port.
To listen to a unix socket, supply a filename instead of port and hostname.
Backlog is the maximum length of the queue of pending connections.
The actual length will be determined by your OS through sysctl settings such as
tcp_max_syn_backlog and somaxconn on linux. The default value of this
parameter is 511 (not 512).
This function is asynchronous. The last parameter callback will be added as
a listener for the &#39;listening&#39; event.
See also .
server.listening
A Boolean indicating whether or not the server is listening for
connections.
server.maxHeadersCount
Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
no limit will be applied.
server.setTimeout(msecs, callback)
Sets the timeout value for sockets, and emits a &#39;timeout&#39; event on
the Server object, passing the socket as an argument, if a timeout
If there is a &#39;timeout&#39; event listener on the Server object, then it
will be called with the timed-out socket as an argument.
By default, the Server&#39;s timeout value is 2 minutes, and sockets are
destroyed automatically if they time out.
However, if you assign a
callback to the Server&#39;s &#39;timeout&#39; event, then you are responsible
for handling socket timeouts.
Returns server.
server.timeout
The number of milliseconds of inactivity before a socket is presumed
to have timed out.
Note that the socket timeout logic is set up on connection, so
changing this value only affects new connections to the server, not
any existing connections.
Set to 0 to disable any kind of automatic timeout behavior on incoming
connections.
Class: http.ServerResponse
This object is created internally by a HTTP server--not by the user. It is
passed as the second parameter to the &#39;request&#39; event.
The response implements the
interface. This is an
with the following events:
Event: &#39;close&#39;
function () { }
Indicates that the underlying connection was terminated before
was called or able to flush.
Event: &#39;finish&#39;
function () { }
Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
handed off to the operating system for transmission over the network. It
does not imply that the client has received anything yet.
After this event, no more events will be emitted on the response object.
response.addTrailers(headers)
This method adds HTTP trailing headers (a header but at the end of the
message) to the response.
Trailers will only be emitted if chunked encoding is used for the
if it is not (e.g., if the request was HTTP/1.0), they will
be silently discarded.
Note that HTTP requires the Trailer header to be sent if you intend to
emit trailers, with a list of the header fields in its value. E.g.,
response.writeHead(200, { &#39;Content-Type&#39;: &#39;text/plain&#39;,
&#39;Trailer&#39;: &#39;Content-MD5&#39; });
response.write(fileData);
response.addTrailers({&#39;Content-MD5&#39;: &#39;8b55ceaf47747b4bca667&#39;});
response.end();
Attempting to set a header field name or value that contains invalid characters
will result in a
being thrown.
response.end([data][, encoding][, callback])
This method signals to the server that all of the response headers and body
that server should consider this message complete.
The method, response.end(), MUST be called on each response.
If data is specified, it is equivalent to calling
followed by response.end(callback).
If callback is specified, it will be called when the response stream
is finished.
response.finished
Boolean value that indicates whether the response has completed. Starts
as false. After
executes, the value will be true.
response.getHeader(name)
Reads out a header that&#39;s already been queued but not sent to the client.
that the name is case insensitive.
This can only be called before headers get
implicitly flushed.
var contentType = response.getHeader(&#39;content-type&#39;);
response.headersSent
Boolean (read-only). True if headers were sent, false otherwise.
response.removeHeader(name)
Removes a header that&#39;s queued for implicit sending.
response.removeHeader(&#39;Content-Encoding&#39;);
response.sendDate
When true, the Date header will be automatically generated and sent in
the response if it is not already present in the headers. Defaults to true.
This should only be
HTTP requires the Date header
in responses.
response.setHeader(name, value)
Sets a single header value for implicit headers.
If this header already exists
in the to-be-sent headers, its value will be replaced.
Use an array of strings
here if you need to send multiple headers with the same name.
response.setHeader(&#39;Content-Type&#39;, &#39;text/html&#39;);
response.setHeader(&#39;Set-Cookie&#39;, [&#39;type=ninja&#39;, &#39;language=javascript&#39;]);
Attempting to set a header field name or value that contains invalid characters
will result in a
being thrown.
When headers have been set with , they will be merged with
any headers passed to , with the headers passed to
given precedence.
// returns content-type = text/plain
const server = http.createServer((req,res) =& {
res.setHeader(&#39;Content-Type&#39;, &#39;text/html&#39;);
res.setHeader(&#39;X-Foo&#39;, &#39;bar&#39;);
res.writeHead(200, {&#39;Content-Type&#39;: &#39;text/plain&#39;});
res.end(&#39;ok&#39;);
response.setTimeout(msecs, callback)
Sets the Socket&#39;s timeout value to msecs.
If a callback is
provided, then it is added as a listener on the &#39;timeout&#39; event on
the response object.
If no &#39;timeout&#39; listener is added to the request, the response, or
the server, then sockets are destroyed when they time out.
assign a handler on the request, the response, or the server&#39;s
&#39;timeout&#39; events, then it is your responsibility to handle timed out
Returns response.
response.statusCode
When using implicit headers (not calling
explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.
response.statusCode = 404;
After response header was sent to the client, this property indicates the
status code which was sent out.
response.statusMessage
When using implicit headers (not calling
explicitly), this property
controls the status message that will be sent to the client when the headers get
flushed. If this is left as undefined then the standard message for the status
code will be used.
response.statusMessage = &#39;Not found&#39;;
After response header was sent to the client, this property indicates the
status message which was sent out.
response.write(chunk[, encoding][, callback])
If this method is called and
has not been called,
it will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.
chunk can be a string or a buffer. If chunk is a string,
the second parameter specifies how to encode it into a byte stream.
By default the encoding is &#39;utf8&#39;. The last parameter callback
will be called when this chunk of data is flushed.
Note: This is the raw HTTP body and has nothing to do with
higher-level multi-part body encodings that may be used.
The first time
is called, it will send the buffered
header information and the first body to the client. The second time
is called, Node.js assumes you&#39;re going to be streaming
data, and sends that separately. That is, the response is buffered up to the
first chunk of body.
Returns true if the entire data was flushed successfully to the kernel
buffer. Returns false if all or part of the data was queued in user memory.
&#39;drain&#39; will be emitted when the buffer is free again.
response.writeContinue()
Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the
event on Server.
response.writeHead(statusCode[, statusMessage][, headers])
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like 404. The last argument, headers, are the response headers.
Optionally one can give a human-readable statusMessage as the second
var body = &#39;hello world&#39;;
response.writeHead(200, {
&#39;Content-Length&#39;: body.length,
&#39;Content-Type&#39;: &#39;text/plain&#39; });
This method must only be called once on a message and it must
be called before
is called.
If you call
before calling this,
the implicit/mutable headers will be calculated and call this function for you.
When headers have been set with , they will be merged with
any headers passed to , with the headers passed to
given precedence.
// returns content-type = text/plain
const server = http.createServer((req,res) =& {
res.setHeader(&#39;Content-Type&#39;, &#39;text/html&#39;);
res.setHeader(&#39;X-Foo&#39;, &#39;bar&#39;);
res.writeHead(200, {&#39;Content-Type&#39;: &#39;text/plain&#39;});
res.end(&#39;ok&#39;);
Note that Content-Length is given in bytes not characters. The above example
works because the string &#39;hello world&#39; contains only single byte characters.
If the body contains higher coded characters then Buffer.byteLength()
should be used to determine the number of bytes in a given encoding.
And Node.js does not check whether Content-Length and the length of the body
which has been transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters
will result in a
being thrown.
Class: http.IncomingMessage
An IncomingMessage object is created by
and passed as the first argument to the &#39;request&#39;
and &#39;response&#39; event respectively. It may be used to access response status,
headers and data.
It implements the
interface, as well as the
following additional events, methods, and properties.
Event: &#39;close&#39;
function () { }
Indicates that the underlying connection was closed.
Just like &#39;end&#39;, this event occurs only once per response.
message.headers
The request/response headers object.
Key-value pairs of header names and values. Header names are lower-cased.
// Prints something like:
// { &#39;user-agent&#39;: &#39;curl/7.22.0&#39;,
host: &#39;127.0.0.1:8000&#39;,
accept: &#39;*/*&#39; }
console.log(request.headers);
Duplicates in raw headers are handled in the following ways, depending on the
header name:
Duplicates of age, authorization, content-length, content-type,
etag, expires, from, host, if-modified-since, if-unmodified-since,
last-modified, location, max-forwards, proxy-authorization, referer,
retry-after, or user-agent are discarded.
set-cookie is always an array. Duplicates are added to the array.
For all other headers, the values are joined together with &#39;, &#39;.
message.httpVersion
In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server.
Probably either &#39;1.1&#39; or &#39;1.0&#39;.
Also message.httpVersionMajor is the first integer and
message.httpVersionMinor is the second.
message.method
Only valid for request obtained from .
The request method as a string. Read only. Example:
&#39;GET&#39;, &#39;DELETE&#39;.
message.rawHeaders
The raw request/response headers list exactly as they were received.
Note that the keys and values are in the same list.
It is not a
list of tuples.
So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
// Prints something like:
// [ &#39;user-agent&#39;,
&#39;this is invalid because there can be only one&#39;,
&#39;User-Agent&#39;,
&#39;curl/7.22.0&#39;,
&#39;Host&#39;,
&#39;127.0.0.1:8000&#39;,
&#39;ACCEPT&#39;,
&#39;*/*&#39; ]
console.log(request.rawHeaders);
message.rawTrailers
The raw request/response trailer keys and values exactly as they were
Only populated at the &#39;end&#39; event.
message.setTimeout(msecs, callback)
Calls message.connection.setTimeout(msecs, callback).
Returns message.
message.statusCode
Only valid for response obtained from .
The 3-digit HTTP response status code. E.G. 404.
message.statusMessage
Only valid for response obtained from .
The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.
message.socket
object associated with the connection.
With HTTPS support, use
to obtain the
client&#39;s authentication details.
message.trailers
The request/response trailers object. Only populated at the &#39;end&#39; event.
message.url
Only valid for request obtained from .
Request URL string. This contains only the URL that is
present in the actual HTTP request. If the request is:
GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
Then request.url will be:
&#39;/status?name=ryan&#39;
If you would like to parse the URL into its parts, you can use
require(&#39;url&#39;).parse(request.url).
& require(&#39;url&#39;).parse(&#39;/status?name=ryan&#39;)
href: &#39;/status?name=ryan&#39;,
search: &#39;?name=ryan&#39;,
query: &#39;name=ryan&#39;,
pathname: &#39;/status&#39;
If you would like to extract the params from the query string,
you can use the require(&#39;querystring&#39;).parse function, or pass
true as the second argument to require(&#39;url&#39;).parse.
& require(&#39;url&#39;).parse(&#39;/status?name=ryan&#39;, true)
href: &#39;/status?name=ryan&#39;,
search: &#39;?name=ryan&#39;,
query: {name: &#39;ryan&#39;},
pathname: &#39;/status&#39;
http.METHODS
A list of the HTTP methods that are supported by the parser.
http.STATUS_CODES
A collection of all the standard HTTP response status codes, and the
short description of each.
For example, http.STATUS_CODES[404] === &#39;Not
Found&#39;.
http.createClient([port][, host])
Stability: 0 - Deprecated: Use
instead.Constructs a new HTTP client. port and host refer to the server to be
connected to.
http.createServer([requestListener])
Returns a new instance of .
The requestListener is a function which is automatically
added to the &#39;request&#39; event.
http.get(options[, callback])
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
is that it sets the method to GET and calls req.end() automatically.
http.get(&#39;/index.html&#39;, (res) =& {
console.log(`Got response: ${res.statusCode}`);
// consume response body
res.resume();
}).on(&#39;error&#39;, (e) =& {
console.log(`Got error: ${e.message}`);
http.globalAgent
Global instance of Agent which is used as the default for all http client
http.request(options[, callback])
Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.
options can be an object or a string. If options is a string, it is
automatically parsed with .
protocol: Protocol to use. Defaults to &#39;http:&#39;.
host: A domain name or IP address of the server to issue the request to.
Defaults to &#39;localhost&#39;.
hostname: Alias for host. To support
hostname is
preferred over host.
family: IP address family to use when resolving host and hostname.
Valid values are 4 or 6. When unspecified, both IP v4 and v6 will be
port: Port of remote server. Defaults to 80.
localAddress: Local interface to bind for network connections.
socketPath: Unix Domain Socket (use one of host:port or socketPath).
method: A string specifying the HTTP request method. Defaults to &#39;GET&#39;.
path: Request path. Defaults to &#39;/&#39;. Should include query string if any.
E.G. &#39;/index.html?page=12&#39;. An exception is thrown when the request path
contains illegal characters. Currently, only spaces are rejected but that
may change in the future.
headers: An object containing request headers.
auth: Basic authentication i.e. &#39;user:password&#39; to compute an
Authorization header.
agent: Controls
behavior. When an Agent is used request will
default to Connection: keep-alive. Possible values:
undefined (default): use
for this host and port.
Agent object: explicitly use the passed in Agent.
false: opts out of connection pooling with an Agent, defaults request to
Connection: close.
createConnection: A function that produces a socket/stream to use for the
request when the agent option is not used. This can be used to avoid
creating a custom Agent class just to override the default createConnection
function. See
for more details.
The optional callback parameter will be added as a one time listener for
the &#39;response&#39; event.
http.request() returns an instance of the
class. The ClientRequest instance is a writable stream. If one needs to
upload a file with a POST request, then write to the ClientRequest object.
var postData = querystring.stringify({
&#39;msg&#39; : &#39;Hello World!&#39;
var options = {
hostname: &#39;&#39;,
path: &#39;/upload&#39;,
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;,
&#39;Content-Length&#39;: postData.length
var req = http.request(options, (res) =& {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding(&#39;utf8&#39;);
res.on(&#39;data&#39;, (chunk) =& {
console.log(`BODY: ${chunk}`);
res.on(&#39;end&#39;, () =& {
console.log(&#39;No more data in response.&#39;)
req.on(&#39;error&#39;, (e) =& {
console.log(`problem with request: ${e.message}`);
// write data to request body
req.write(postData);
req.end();
Note that in the example req.end() was called. With http.request() one
must always call req.end() to signify that you&#39;re done with the request -
even if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an &#39;error&#39; event is emitted
on the returned request object. As with all &#39;error&#39; events, if no listeners
are registered the error will be thrown.
There are a few special headers that should be noted.
Sending a &#39;Connection: keep-alive&#39; will notify Node.js that the connection to
the server should be persisted until the next request.
Sending a &#39;Content-length&#39; header will disable the default chunked encoding.
Sending an &#39;Expect&#39; header will immediately send the request headers.
Usually, when sending &#39;Expect: 100-continue&#39;, you should both set a timeout
and listen for the &#39;continue&#39; event. See RFC2616 Section 8.2.3 for more
information.
Sending an Authorization header will override using the auth option
to compute basic authentication.}

我要回帖

更多关于 httpclient 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信