-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathw4restapi.js
89 lines (73 loc) · 1.83 KB
/
w4restapi.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var http = require('http');
module.exports =
{
call: function(options)
{
var uri = options.path;
var formData = '';
var httpEntity = false;
if (options.parameters)
{
for (var parameterName in options.parameters)
{
var parameterValue = options.parameters[parameterName];
formData += parameterName + '=' + parameterValue;
formData += '&';
}
if (formData.length > 0)
{
formData = formData.slice(0, -1);
}
}
var httpOptions =
{
hostname: options.hostname || 'localhost',
port: options.port || 7705,
path: uri,
method: options.method || 'GET'
};
if ('authUser' in options)
{
httpOptions.auth = options.authUser + ':' + options.authPassword
}
if (httpOptions.method == 'POST' || httpOptions.method == 'PUT')
{
httpEntity = formData;
}
if (httpOptions.method == 'DELETE')
{
httpEntity = ' ';
}
if (httpOptions.method == 'GET' || httpOptions.method == 'DELETE')
{
httpOptions.path += '?' + formData
}
if (httpEntity)
{
httpOptions.headers =
{
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': httpEntity.length,
}
}
console.log(httpOptions.method + ' ' + httpOptions.path);
var request = http.request(httpOptions, function(response)
{
response.setEncoding('utf8');
response.on('data', function (data)
{
console.log('\nRESPONSE:\n' + JSON.stringify(JSON.parse(data), null, 2));
});
});
request.on('error', function(error)
{
console.log('problem with request: ' + error.message);
});
if (httpEntity)
{
console.log('BODY: ' + httpEntity);
request.write(httpEntity + '\n\n');
}
request.end();
}
}