安裝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);
|