方法说明:
函数的功能室作为客户端向http服务器发起请求。
语法:
复制代码 代码如下:
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();