In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/03 Report--
HTTP is not based on a specific language, it is a general application layer protocol. Different languages have different implementation details, but the idea is the same. NodeJS, as a host environment and JavaScript as the host language, also has its own set of standards. This article will introduce the Http module in nodeJS in detail.
Agent
[new Agent ([options])]
Configuration options for the options agent. There are the following fields: keepAlive keeps socket available even without requests so that they can be used by future requests without having to establish a new TCP connection. The default is false. KeepAliveMsecs when the keepAlive option is used, this option specifies the initial delay of the TCP Keep-Alive packet. This option has no effect when the keepAlive option is false or undefined. The default is 1000. MaxSockets the maximum number of socket allowed per host. The default is Infinity. The maximum number of socket that maxFreeSockets is allowed to open when idle. Valid only if keepAlive is true. The default is 256
The default http.globalAgent options used by http.request () are their respective default values
To configure any of these, you need to create a custom http.Agent instance
[agent.createConnection (options [, callback])]
The option that options contains the connection details callback receives the callback function of the created socket. Callback has (err, stream) parameters that return:
Create a socket or stream for HTTP requests
By default, the function is similar to net.createConnection (). But if you expect more flexibility, the custom agent can override the method
Socket or stream can be obtained in two ways: return from this function or pass in callback
[agent.destroy ()]
Destroy any socket currently being used by the agent
You don't usually have to do this. However, if you are using an agent with keepAlive enabled, it is best to explicitly close the agent when it is determined that it is no longer being used. Otherwise, socket may remain open for a long time before the server terminates them
[agent.freeSockets]
Returns an object containing the socket array currently waiting to be used by keepAlive-enabled agents. Do not modify this property
[agent.getName (options)]
The option for options to provide information to the name generator. The domain name or IP address of the server to which the host request is sent. The port of the port remote server. LocalAddress binds the local interface for the network connection when sending the request. Return:
Gets a unique name for the collection of request options to determine whether a connection can be reused. For HTTP agents, return host:port:localAddress. For HTTPS agents, the name contains CA, certificate, password, and other HTTPS/TLS-specific options for determining socket reusability
[agent.maxFreeSockets]
The default is 256. For keepAlive-enabled agents, this property sets the maximum number of free socket to keep
[agent.maxSockets]
There is no limit by default. This property sets the maximum number of concurrent socket opened by the agent for each source. The source is a combination of 'host:port' or' host:port:localAddress'
[agent.requests]
Returns an object containing the request queue that has not yet been assigned to the socket. Don't modify it.
[agent.sockets]
Returns an object containing the socket array currently being used by the agent. Don't modify it.
Request
[http.ClientRequest]
The object is created and returned inside http.request (). It represents a request that is being processed and whose request header has entered the queue. The request header can still be modified using setHeader (name, value), getHeader (name), and removeHeader (name) API. The actual request header is sent with the first block or when the connection is closed
To get the response, add a listener to the request object for the 'response' event. When the response header is received, the 'response' event is triggered from the request object. The 'response' event is executed with a parameter, which is an instance of http.IncomingMessage. During the 'response' event, you can add listeners to the response object, such as listening for the' data' event
If no 'response' event handler is added, the response is discarded as a whole. If you add a 'response' event handler, you must run out of data for the response object, either by calling response.read (), or by adding a' data' event handler, or by calling the .handler () method. The 'end' event is triggered when the data is consumed. Memory is consumed before the data is read, which may cause a 'process out of memory' error
[note] Node.js does not check whether the length of the Content-Length is equal to that of the transmitted request body
Var http = require ('http'); var server = http.createServer (function (req, res) {console.log (req.url); / /' / 'console.log (req.httpVersion); / / 1.1console.log (req.method); / / GET / / {"host": "127.0.0.1Vl5000", "connection": "keep-alive", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64)" X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 "," accept ":" paired wicked picpathway, paired wicked picpathway, paired wayward picpathway, paired wayward picpathway, and "referer": "http://127.0.0.1:5000/","accept-encoding":"gzip, deflate, sdch, br", "accept-language": "zh-CN,zh;q=0.8,en". Qroom0.6 "} console.log (JSON.stringify (req.headers)); res.end ('ok');}); server.listen (5000)
[abort event]
Triggered when the request has been terminated by the client. This event is triggered only when abort () is called for the first time
[aborted event]
Triggered when the request has been terminated by the server and the network socket has been closed
[connect event]
Response socket head
Triggered when the server responds to a CONNECT request. If the event is not monitored, the client that receives the CONNECT method closes the connection
[continue event]
Triggered when the server sends a HTTP response of 100 Continue, usually because the request contains Expect: 100-continue. This is the instruction that the client is going to send the request subject
[response event]
Response
Triggered when the response to the request is received. The event is triggered only once
[socket event]
Socket
Triggered when socket is assigned to a request
[upgrade event]
Response socket head
Triggered whenever the server responds to a upgrade request. If the event is not monitored, the client that receives the upgrade request header closes the connection
[request.abort ()]
Mark request is terminated. Calling this method will cause the remaining data in the response to be discarded and the socket destroyed.
[request.aborted]
If the request has been terminated, the value of this property is the time the request was terminated, from 1 January 1970 00:00:00 UTC to the current milliseconds
[request.end ([data] [, encoding] [, callback])]
Data | encoding callback
End sending request. If some of the request bodies have not been sent, they are refreshed to the stream. If the request is chunked, the termination character'0\ r\ n\ r\ n' is sent.
If data is specified, it is equivalent to calling response.write (data, encoding) and then request.end (callback).
If callback is specified, it will be called when the request flow ends
[request.flushHeaders ()]
Refresh request header
For efficiency reasons, Node.js usually caches the request header until request.end () is called or the first block of request data is written. Node.js then packages the request header and data into a single TCP packet. That's usually expected (because it saves TCP round trips), unless the first block is sent a long time later. Request.flushHeaders () can bypass the optimal choice and start the request in advance
[request.setNoDelay ([noDelay])]
NoDelay
Once socket is assigned to the request and connected, socket.setNoDelay () will be called
[request.setSocketKeepAlive ([enable] [, initialDelay])]
Enable initialDelay
Once socket is assigned to the request and connected, socket.setKeepAlive () will be called
[request.setTimeout (timeout [, callback])]
Timeout optional function that is called when a timeout occurs. Equivalent to binding to the timeout event to return request
Once socket is assigned to the request and connected, socket.setTimeout () will be called
[request.write (chunk [, encoding] [, callback])]
The chunk | encoding parameter is optional and is valid only if chunk is a string. The default 'utf8' callback parameter is optional, and the call returns request when the data block is refreshed.
Sends a data block of the request body. By calling this method multiple times, a request subject can be sent to a server, in which case, when creating a request, it is recommended to use the ['Transfer-Encoding',' chunked'] request header
Server
Most nodejs developers choose nodejs for the purpose of developing web server. With the help of the http module, a ultra-mini web server can be done in a few lines of code.
[http.createServer ([requestListener])]
This method creates and returns a HTTP server object
RequestListener indicates the callback function that monitors the client connection.
Var server = http.createServer (function (req,res) {})
[server.listen (port [, hostname] [, backlog] [, callback])]
This method starts to receive connections on the specified port and hostname
Port indicates the port to be monitored. If it is not set, the port will be automatically assigned by the system.
If you omit the hostname hostname, the server will receive an address (INADDR_ANY) pointing to any IPv4
To monitor a unix socket, you need to provide a file name instead of a hostname and port
If the backlog backlog is the maximum length of the waiting queue for connection, that is, how many clients are allowed to exist in the queue. The actual length is determined by the operating system's sysctl setting. The default parameter value is 511
The last parameter, callback, is an asynchronous function that is added to the listening event as an event listener.
Server.listen (5000)
[request event]
Triggered when a client sends a request to the host and port
Parameter request: an instance of http.IncomingMessage, through which we can get some information about this request, such as header information, data, etc.
Parameter response: an instance of http.ServerResponse through which we can return a response to the client output of the request
Server.on ('request',function (request,response) {console.log (' received message');})
Since the argument to createServer () is requestListener, the callback function in the request event can be written as the argument to createServer ().
Var server = http.createServer (function (req,res) {console.log ('received message');})
Therefore, using the above methods, you can create a simple server
Var http = require ('http'); var server = http.createServer (function (req,res) {console.log (' received message'); server.listen (5000)
Enter 127.0.0.1bure5000 in the browser address bar, and the console will display the words "received message"
[checkContinue event]
Request response
Triggered whenever a request is received with a HTTP Expect: 100-continue request header. If the event is not monitored, the server automatically responds to 100 Continue
When handling this event, response.writeContinue () is called if the client should continue to send the request body, otherwise an appropriate HTTP response (such as a 400 error request) is generated.
[note] when the event is triggered and processed, the request event will not be triggered
[checkExpectation event]
Request response
Triggered whenever a request is received with a HTTP Expect request header (the value is not 100-continue). If the event is not monitored, the server automatically responds to 417 Expectation Failed.
[note] when the event is triggered and processed, the request event will not be triggered
[clientError event]
The exception socket socket parameter is the net.Socket object on which the error occurred
If the client triggers an error event, it is passed here. The listener for this event is responsible for shutting down or destroying the underlying socket. For example, the user may want to turn off socket more gently with a HTTP '400 Bad Request' response, rather than suddenly severing the connection
By default, socket is destroyed immediately when an exception is requested
Var http = require ('http'); var server = http.createServer ((req, res) = > {res.end ();}); server.on (' clientError', (err, socket) = > {socket.end ('HTTP/1.1 400Bad Request\ n\ r\ n\ n'); server.listen (8000)
When the 'clientError' event occurs, there are no request or response objects, so any HTTP responses sent, including response headers and content, must be written directly to the socket object. Note that make sure that the response is a properly formatted HTTP response message
[close event]
Triggered when the server shuts down
[connect event]
Request HTTP request, same as request event. Network socket between the socket server and the client. The first packet of the head stream may be empty.
Triggered when a client sends an HTTP CONNECT request. If the event is not monitored, the client that sent the CONNECT request closes the connection
When this event is triggered, there is no data event listener on the requested socket, which means that the data event listener needs to be bound to process the data sent to the server on the socket
[connection event]
Socket
Triggered when a new TCP stream is created. Socket is an object of type net.Socket. Typically, users do not need to access this event. Note that because of the way the protocol parser is bound to socket, socket does not fire the 'readable' event. Socket can also be accessed through request.connection
[upgrade event]
Request HTTP request, which is the same as the 'request' event. Network socket between the socket server and the client. The first packet of the head stream may be empty.
Triggered whenever a client sends a HTTP upgrade request. If the event is not monitored, the client that sent the upgrade request closes the connection
When this event is triggered, there is no 'data' event listener on the requested socket, which means that the data' event listener needs to be bound to process the data sent to the server on the socket
[server.close ([callback])]
Stop the server from receiving new connections
[server.listening]
Returns a Boolean value indicating whether the server is listening for a connection
[server.maxHeadersCount]
The default is 2000
Limit the maximum number of request headers, which defaults to 2000. If set to 0, there is no limit
[server.setTimeout ([msecs] [, callback])]
Msecs defaults to 120000 (2 returns server
Sets the timeout for socket. If a timeout occurs, the 'timeout' event of the server object is triggered and socket is passed as a parameter
By default, the server's timeout is 2 minutes, and the socket after the timeout is automatically destroyed. However, if you assign a callback function to the server's' timeout' event, the timeout must be handled explicitly
[server.timeout]
Timeout, in milliseconds. Default is 120000 (2 minutes)
The number of idle milliseconds that socket is considered to have timed out. Set the value to 0 to disable the timeout behavior of the request connection
[note] socket's timeout logic is set on connections, so changing this value only affects new connections to the server, not any existing connections.
Response
The object is created inside the HTTP server. It is passed in the 'request' event as the second parameter. This class implements (rather than inherits from) a writable stream interface
Var http = require ('http'); var server = http.createServer (function (req, res) {res.writeHead (200,{' Content-Type': 'text/plain;charset=utf-8'}); res.end (' Little match'); server.listen (8000)
[close event]
Triggered when the underlying connection is terminated before response.end () is called or can be refreshed
[finish event]
Triggered when the response has been sent. More specifically, the event is triggered when the response header and the last part of the response body have been handed over to the operating system for transmission over the network. This does not mean that the client has received anything. After this event is triggered, no other events are triggered on the response object
[response.addTrailers (headers)]
Headers
This method adds the HTTP tail response header (a response header at the end of the message) to the response.
The tail response header is sent only if the response is chunked; otherwise (for example, the request is HTTP/1.0), the tail response header is discarded.
[note] before sending the tail response header, you need to send the Trailer response header with a list of tail response header fields in the value
Response.writeHead (200,{ 'Content-Type':' text/plain', 'Trailer':' Content-MD5'}); response.write (fileData); response.addTrailers ({'Content-MD5':' 7895bf4b8828b55ceaf47747b4bca667'}); response.end ()
If the name or value of the trailing response header field contains invalid characters, a TypeError error is thrown
[response.end ([data] [, encoding] [, callback])]
| data | encoding if data is specified, it is equivalent to calling response.end (callback) callback after calling response.write (data, encoding). If callback is specified, it is called when the response flow ends. |
This method notifies the server that all response headers and response subjects have been sent, that is, the server considers it completed. The response.end () method must be called for each response
[response.finished]
Returns a Boolean value indicating whether the response has been completed. The default is false. After response.end () is executed, the value becomes true
[response.getHeader (name)]
Name returns:
Read a response header that has been queued but not yet sent to the client
[note] names are not case-sensitive
Var contentType = response.getHeader ('content-type')
[response.getHeaderNames ()]
Returns an array of response header names
Response.setHeader ('Foo',' bar'); response.setHeader ('Set-Cookie', [' foo=bar', 'bar=baz']); var headerNames = response.getHeaderNames (); / / headerNames = = [' foo', 'set-cookie']
[response.getHeaders ()]
Returns an array of response headers
Response.setHeader ('Foo',' bar'); response.setHeader ('Set-Cookie', [' foo=bar', 'bar=baz']); var headers = response.getHeaders (); / / headers = = {foo:' bar', 'set-cookie': [' foo=bar', 'bar=baz']}
[response.hasHeader (name)]
Whether to include the current response header
Var hasContentType = response.hasHeader ('content-type')
[response.headersSent]
Returns a Boolean (read-only). True if the response header has been sent, otherwise false
[response.removeHeader (name)]
Remove a response header from an implicitly sent queue
Response.removeHeader ('Content-Encoding')
[response.sendDate]
When true, if there is no date response header in the response header, the date response header is automatically generated and sent. The default is true.
This property can only be disabled during testing because the HTTP response needs to include a date response header
[response.setHeader (name, value)]
Name value |
Sets a value for an implicit response header. If the response header already exists, the value is overwritten. If you want to send multiple response headers with the same name, use an array of strings
Response.setHeader ('Content-Type',' text/html'); response.setHeader ('Set-Cookie', [' type=ninja', 'language=javascript'])
If the name or value of the response header field contains invalid characters, a TypeError error is thrown
The response header set by response.setHeader () is merged with that set by response.writeHead (), and response.writeHead () takes precedence.
[response.setTimeout (msecs [, callback])]
Msecs returns response
Set the timeout of socket to msecs. If a callback function is provided, it is added as a listener to the 'timeout' event of the response object
If no 'timeout' listener is added to the request, response, or server, the socket will be destroyed after the timeout. If a callback function is assigned on the request, response, or server's' timeout' event, then the timed-out socket must be explicitly handled
[response.statusCode]
When an implicit response header is used (without an explicit call to response.writeHead ()), this property controls the status code that will be sent to the client when the response header is refreshed
Response.statusCode = 404
After the response header is sent to the client, this property represents the status code issued
[response.statusMessage]
When an implicit response header is used (there is no explicit call to response.writeHead ()), this property controls the status information that will be sent to the client when the response header is refreshed. If the value is undefined, the standard information of the status code is used
Response.statusMessage = 'Not found'
After the response header is sent to the client, this property represents the status information that is sent
[response.write (chunk [, encoding] [, callback])]
Chunk | encoding callback returns:
If the method is called and response.writeHead () is not called, it switches to implicit response header mode and refreshes the implicit response header.
This method sends a response body. It can be called multiple times to provide a continuous response body fragment
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. Encoding defaults to 'utf8'. Callback is called when the data block is refreshed.
[note] this is the original HTTP body and has nothing to do with the advanced principal encoding that may be used
[response.write ()]
When called for the first time, the buffered response header information and the first piece of data of the response body are sent to the client. When response.write () is called for the second time, Node.js processes the data as a stream and sends them separately. That is, the response is buffered to the first block of the response body.
If all data is successfully flushed to the kernel buffer, true is returned. Returns false if all or part of the data is still queued in memory. When the buffer is idle again, the 'drain' event is triggered
[response.writeContinue ()]
Send a HTTP/1.1 100Continue message to the client, indicating that the request subject can start sending
[response.writeHead (statusCode [, statusMessage] [, headers])]
StatusCode status code is a three-digit HTTP status code, such as 404statusMessage statusMessage is optional state description headers headers is the response header
Send a response header to the request
Var body = 'hello world';response.writeHead (200,{' Content-Length': Buffer.byteLength (body), 'Content-Type':' text/plain'})
This method can only be called once in the message and must be called before response.end () is called.
If response.write () or response.end () is called before the method is called, the implicit response header is processed and the function is called.
The response header set by response.setHeader () is merged with the response header set by response.writeHead (), and response.writeHead () takes precedence
/ / return content-type = text/plainvar server = http.createServer ((req, res) = > {res.setHeader ('Content-Type',' text/html'); res.setHeader ('X bar', 'bar'); res.writeHead (200,{' Content-Type': 'text/plain'}); res.end (' ok');})
[note] Content-Length is in bytes (not characters). If the response body contains characters with advanced encoding, Buffer.byteLength () should be used to determine the number of bytes in a given encoding. Node.js does not check whether the Content-Length is the same length as the response body that has been sent.
If the name or value of the response header field contains invalid characters, a TypeError error is thrown
IncomingMessage
The 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 be used to access response status, message headers, and data. It implements a readable stream interface.
[aborted event]
Triggered when the request has been terminated by the client and the network socket has been closed
[close event]
Triggered when the underlying connection is closed. As with the end event, this event is triggered only once per response
[message.destroy ([error])]
Call the destroy () method on the socket that received the IncomingMessage. If error is provided, the error event is triggered and the listener passing error as an argument to the event
[message.headers]
Object of request header or response header
The name of the header information is paired with the key value of the value. The name of the header information is lowercase
/ / {'user-agent':' curl/7.22.0',// host: '127.0.0.1 accept:' * / *'} console.log (request.headers)
[message.httpVersion]
In a server request, this property returns the version of HTTP sent by the client. In the client response, this property returns the HTTP version of the server to which you are connected. Possible values are '1.1' or '1.0'
Message.httpVersionMajor returns the first integer value of the HTTP version, and message.httpVersionMinor returns the second integer value of the HTTP version
[message.method]
Returns a string representing the requested method. This property is read-only. For example: 'GET',' DELETE'.
[note] valid only in requests returned by http.Server.
[message.rawHeaders]
The original list of request headers or response headers received.
[note] the key and value are in the same list. Even digits are keys and odd digits are corresponding values.
The name of the header information will not be converted to lowercase, and duplicates will not be merged
/ / ['user-agent',//' this is invalid because there can be only one',// 'User-Agent',//' curl/7.22.0',// 'Host',//' 127.0.0.1 User-Agent',// 8000 pounds / 'ACCEPT',//' * /] console.log (request.rawHeaders)
[message.rawTrailers]
The key and value of the original Trailer request header or response header received. Is assigned only on the 'end' event
[message.setTimeout (msecs, callback)]
Msecs callback returns message
Call message.connection.setTimeout (msecs, callback)
[message.socket]
Returns the net.Socket object associated with the connection.
Through the support of HTTPS, use request.socket.getPeerCertificate () to obtain the authentication information of the client
[message.statusCode]
Returns a three-digit HTTP response status code. Such as 404
[note] it is only valid in the response returned by http.ClientRequest.
[message.statusMessage]
Valid only in the response returned by http.ClientRequest.
Returns a HTTP response status message (reason description). Such as OK or Internal Server Error
[message.trailers]
Returns the Trailer request header or response header object. Is assigned only on the 'end' event
[message.url]
Returns the requested URL string. Contains only the URL in the actual HTTP request
[note] valid only in requests returned by http.Server
HTTP
[http.METHODS]
Returns the list of HTTP methods supported by the parser
[http.STATUS_CODES]
Returns a collection of standard HTTP response status codes and their short descriptions
Http.STATUS_CODES [404] = Not Found'
[http.createServer ([requestListener])]
RequestListener requestListener is a function that is automatically added to the 'request' event return:
Returns a newly created http.Server instance
[http.get (options [, callback])]
Options | callback returns:
Because most requests are GET requests without a request body, Node.js provides this convenient method. The only difference between this method and http.request () is that it sets the request method to GET and automatically calls req.end (). Note that the response data must be consumed in the callback
Only one parameter is passed in when callback is called, which is an instance of http.IncomingMessage
Var http = require ('http'); http.get (' http://127.0.0.1:3000', function (res) {console.log (res.statusCode); / / 200})
[http.globalAgent]
A global instance of Agent as the default Agent for all HTTP client requests
[http.request (options [, callback])]
Options | options is an object or string. If it is a string, it is automatically parsed using url.parse () to parse the protocol used by protocol. The default is http:. The domain name or IP address of the server to which the host request is sent. The default is localhost. An alias for hostname host. To support url.parse (), hostname is superior to host. The family of IP addresses that family uses when parsing host and hostname. Valid values are 4 or 6. When not specified, the ports of both IPv4 and V6 port remote servers are used. The default is 80. LocalAddress is the local interface bound to the network connection. SocketPath Unix domain Socket (using host:port or socketPath). Method specifies the string of the HTTP request method. The default is' GET'. The path to the path request. The default is'/'. The query string, if any, should be included. Such as'/ index.html?page=12'. An exception is thrown when the requested path contains illegal characters. Currently, only null characters will be rejected, but may change in the future. The headers contains the object of the request header. Auth basic authentication, such as' user:password', is used to calculate the Authorization request header. Agent | controls the behavior of Agent. Possible values are: undefined (default): use http.globalAgent for this host and port. Agent object: explicitly uses the incoming Agent. False: create a new Agent with default values. CreateConnection creates a socket or stream for the request when the agent option is not used. This can be used to avoid simply creating a custom Agent class to override the default createConnection function. See agent.createConnection () for details. Timeout: specifies the number of milliseconds that socket times out. It sets the timeout for socket to wait for a connection. The callback optional callback parameter is added to the 'response' event as a single listener
Node.js maintains multiple connections for each server to make HTTP requests. This function allows requests to be made explicitly. Http.request () returns an instance of the http.ClientRequest class. The ClientRequest instance is a writable stream. If you need to upload a file through a POST request, write to the ClientRequest object
Https
HTTPS is a TLS/SSL-based version of HTTP. In Node.js, it is implemented as a separate module
[server.setTimeout ([msecs] [, callback])]
Msecs Defaults to 120000 (2 minutes). Callback
[server.timeout]
Defaults to 120000 (2 minutes)
[server.keepAliveTimeout]
Defaults to 5000 (5 seconds)
[server.close ([callback])]
Callback
[server.listen ([port] [, host] [, backlog] [, callback])]
Port hostname backlog callback
[https.createServer (options [, requestListener])]
Options requestListener
[https.get (options [, callback])]
Options | options is an object or string. If it is a string, it is automatically parsed by callback by url.parse ()
Similar to http.get (), but used for HTTPS
The parameter options can be an object or a string. If the parameter options is a string, it is automatically parsed by url.parse ()
[https.globalAgent]
A global instance of https.Agent for all HTTPS client requests
[https.request (options [, callback])]
Options | protocol Defaults to https: port Defaults to 443. Agent Defaults to https.globalAgent.callback
Initiate a request to a secure server
The parameter options can be an object or a string. If a string, it is automatically parsed by url.parse ()
Application
[simple GET request]
Var https = require ('https'); https.get (' https://www.cnblogs.com/', function (res) {var data ='; res.setEncoding ('utf8'); res.on (' data', function (chunk) {data + = chunk;}); res.on ('end', function () {console.log (data);});})
[simple POST request]
Var http = require ('http'); var querystring = require (' querystring') Var createClientPostRequest = function () {var options = {method: 'POST', protocol:' http:', hostname: '127.0.0.1, port:' 3000, path:'/ post', headers: {"connection": "keep-alive" "content-type": "application/x-www-form-urlencoded"}} / / data sent to the server var postBody = {a:'1'}; / / create client request var client = http.request (options, function (res) {/ / final output: Server got client data: nick=chyingp res.pipe (process.stdout);}) / / for the body of the message sent, remember to use querystring.stringify () to process client.write (querystring.stringify (postBody)); client.end ();}; / / server program, which is only responsible for sending back client data var server = http.createServer (function (req, res) {res.write ('Server got client data:'); req.pipe (res);}); server.listen (3000, createClientPostRequest)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.