安装http
1
|
nmp install http
|
函数封装(可直接拿去进行使用)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
var http
=
require(
'http'
);
function nodePostGetRequest(HOST, PORT, method, bodydata, callBackFunction, path, cookie) {
/
/
把将要发送的body转换为json格式
var body
=
bodydata;
var bodyString
=
JSON.stringify(body);
/
/
http 头部
var headers
=
{
'Content-Type'
:
'application/json'
,
'Content-Length'
: bodyString.length,
'Cookie'
: cookie
};
/
/
用与发送的参数类型
var options
=
{
host: HOST,
/
/
ip
port: PORT,
/
/
port
path: path,
/
/
get方式使用的地址
method: method,
/
/
get方式或post方式
headers: headers
};
var req
=
http.request(options, function(res) {
res.setEncoding(
'utf-8'
);
var responseString
=
'';
res.on(
'data'
, function(data) {
responseString
+
=
data;
});
res.on(
'end'
, function() {
/
/
这里接收的参数是字符串形式,需要格式化成json格式使用
var resultObject
=
JSON.parse(responseString);
console.log(
'-----resBody-----'
, resultObject);
callBackFunction(responseString);
});
req.on(
'error'
, function(e) {
/
/
TODO: handle error.
console.log(
'-----error-------'
, e);
});
});
req.write(bodyString);
req.end();
}
|
nodePostGetRequest函数解析(使用方法)
1
2
3
4
5
6
7
|
HOST:ip地址
PORT:端口号
method:请求方式(get或post)
bodydata:进去时发送的内容(当为get请求时可以传null。)
callBackFunction:回调函数(请求发送后进行数据接收。需要自己实现对数据的处理)
path:请求路径(post请求可以为空。get不可为空)
cookie:需要携带的cookie
|
使用案例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var datapost
=
{
"BODY"
: {
"Header"
: {
},
"Body"
: {
}
}
};
nodePostGetRequest(HOST, PORT,
"POST"
, datapost, detalCall, '', mycookie);
或
var path
=
"";
nodePostGetRequest(HOST, PORT,
"GET"
, "", dealCallback, path, mycookie);
|