您的位置:首页 > 理论基础 > 计算机网络

node.js中的http.request方法使用说明

2017-03-03 14:06 781 查看
http.get(options, callback)


由于该方法属于http模块,使用前需要引入http模块(var http= require(“http”) )

接收参数:

option 数组对象,包含以下参数:

host: 表示请求网站的域名或IP地址(请求的地址)。 默认为'localhost'。

hostname: 服务器名称,主机名是首选的值。

port: 请求网站的端口,默认为 80。

localAddress: 建立网络连接的本地

socketPath: Unix Domain Socket(Domain套接字路径)

method: HTTP请求方法,默认是 ‘GET'。

path: 请求的相对于根的路径,默认是'/'。QueryString应该包含在其中。例如:/index.html?page=12

headers: 请求头对象。

auth: Basic认证(基本身份验证),这个值将被计算成请求头中的 Authorization 部分。

callback : 回调,传递一个参数,为 http.ClientResponse的实例。http.request 返回一个 http.ClientRequest 的实例。

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('data\n');
req.write('data\n');
req.end();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: