接收参数:
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请求
POST请求
- var http = require('http');
- var qs = require('querystring');
- var data = {
- a: 123,
- time: new Date().getTime()};//这是需要提交的数据
- var content = qs.stringify(data);
- var options = {
- hostname: '127.0.0.1',
- port: 10086,
- path: '/pay/pay_callback?' + content,
- method: 'GET'
- };
- 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);
- });
- req.end();
POST请求
- var http = require('http');
- var qs = require('querystring');
- var post_data = {
- a: 123,
- time: new Date().getTime()};//这是需要提交的数据
- var content = qs.stringify(post_data);
- var options = {
- hostname: '127.0.0.1',
- port: 10086,
- path: '/pay/pay_callback',
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
- }
- };
- 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(content);
- req.end();