nodejs http.request 发送请求demo

接收参数:

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


GET请求  
Js代码   收藏代码
  1. var http = require('http');  
  2.   
  3. var qs = require('querystring');  
  4.   
  5. var data = {  
  6.     a: 123,  
  7.     time: new Date().getTime()};//这是需要提交的数据  
  8.   
  9.   
  10. var content = qs.stringify(data);  
  11.   
  12. var options = {  
  13.     hostname: '127.0.0.1',  
  14.     port: 10086,  
  15.     path: '/pay/pay_callback?' + content,  
  16.     method: 'GET'  
  17. };  
  18.   
  19. var req = http.request(options, function (res) {  
  20.     console.log('STATUS: ' + res.statusCode);  
  21.     console.log('HEADERS: ' + JSON.stringify(res.headers));  
  22.     res.setEncoding('utf8');  
  23.     res.on('data'function (chunk) {  
  24.         console.log('BODY: ' + chunk);  
  25.     });  
  26. });  
  27.   
  28. req.on('error'function (e) {  
  29.     console.log('problem with request: ' + e.message);  
  30. });  
  31.   
  32. req.end();  


POST请求  
Js代码   收藏代码
  1. var http = require('http');  
  2.   
  3. var qs = require('querystring');  
  4.   
  5. var post_data = {  
  6.     a: 123,  
  7.     time: new Date().getTime()};//这是需要提交的数据  
  8.   
  9.   
  10. var content = qs.stringify(post_data);  
  11.   
  12. var options = {  
  13.     hostname: '127.0.0.1',  
  14.     port: 10086,  
  15.     path: '/pay/pay_callback',  
  16.     method: 'POST',  
  17.     headers: {  
  18.         'Content-Type''application/x-www-form-urlencoded; charset=UTF-8'  
  19.     }  
  20. };  
  21.   
  22. var req = http.request(options, function (res) {  
  23.     console.log('STATUS: ' + res.statusCode);  
  24.     console.log('HEADERS: ' + JSON.stringify(res.headers));  
  25.     res.setEncoding('utf8');  
  26.     res.on('data'function (chunk) {  
  27.         console.log('BODY: ' + chunk);  
  28.     });  
  29. });  
  30.   
  31. req.on('error'function (e) {  
  32.     console.log('problem with request: ' + e.message);  
  33. });  
  34.   
  35. // write data to request body  
  36. req.write(content);  
  37.   
  38. req.end();  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值