Home >Web Front-end >JS Tutorial >Instructions for using the http.request method in node.js_node.js

Instructions for using the http.request method in node.js_node.js

WBOY
WBOYOriginal
2016-05-16 16:27:141589browse

Method description:

The function room of the function acts as a client to initiate a request to the HTTP server.

Grammar:

Copy code The code is as follows:

http.get(options, callback)

Since this method belongs to the http module, the http module needs to be introduced before use (var http= require("http") )

Receive parameters:

option array object, containing the following parameters:

Host: Represents the domain name or IP address (requested address) of the requested website. Defaults to 'localhost'.

Hostname: Server name, hostname is the preferred value.

port: The port of the requested website, the default is 80.

localAddress: Local location to establish network connection

socketPath: Unix Domain Socket (Domain socket path)

method: HTTP request method, the default is ‘GET’.

path: The requested path relative to the root, the default is '/'. QueryString should be included in it. For example: /index.html?page=12

headers: Request header object.

auth: Basic authentication (Basic authentication), this value will be calculated as the Authorization part of the request header.

callback: callback, passing a parameter, which is an instance of http.ClientResponse. http.request returns an instance of http.ClientRequest.

Example:

Copy code The code is as follows:

var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};

var req = http.request(options, function(res) {
console.log('STATUS: ' res.statusCode);
console.log('HEADERS: ' JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' chunk);
});
});

req.on('error', function(e) {
console.log('problem with request: ' e.message);
});

// write data to request body
req.write('datan');
req.write('datan');
req.end();
Statement:
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