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


方法说明:

函数的功能是作为客户端向HTTP服务器发起请求。

语法:

1 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 的实例。

 

例子:

 1 var options = { 
 2 hostname: 'www.google.com', 
 3 port: 80, 
 4 path: '/upload', 
 5 method: 'POST' 
 6 }; 
 7  
 8 var req = http.request(options, function(res) { 
 9 console.log('STATUS: ' + res.statusCode); 
10 console.log('HEADERS: ' + JSON.stringify(res.headers)); 
11 res.setEncoding('utf8'); 
12 res.on('data', function (chunk) { 
13 console.log('BODY: ' + chunk); 
14 }); 
15 }); 
16  
17 req.on('error', function(e) { 
18 console.log('problem with request: ' + e.message); 
19 }); 
20  
21 // write data to request body 
22 req.write('data\n'); 
23 req.write('data\n'); 
24 req.end();

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM