-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy path00207-MacchinaJSNetReference.page
504 lines (286 loc) · 13.3 KB
/
00207-MacchinaJSNetReference.page
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
JavaScript Network API Reference
AAAAMacchinaIO
!!!HTTPRequest and HTTPResponse Objects
HTTPRequest objects are used to either send a HTTP or HTTPS request to a web server,
or to obtain information about the HTTP request in a servlet or server page.
As of the 0.7.0 release, the HTTPRequest object has been moved into a separate
<*net*> module, available through the <*com.appinf.osp.js.net*> bundle.
You'll have to import the <*net*> module in your script before being able to
use the HTTPRequest object.
To send a HTTP request, create a new HTTPRequest object, using the <[HTTPRequest]>
constructor function. The constructor takes three optional arguments,
a request method (e.g., "GET"), a URI (e.g., "https://macchina.io") and the
HTTP version string (e.g., "HTTP/1.1"). All these values can be set at a later
time as well, via properties.
HTTP requests can be sent in blocking or asynchronous mode. In blocking mode,
the script has to wait until the HTTP request completes. In asynchronous mode,
the HTTP request is sent in a separate thread, and the script is notified
of the result via a callback function.
Here is an example for a synchronous request:
var net = require('net');
var request = new net.HTTPRequest('GET', 'https://macchina.io');
var response = request.send();
logger.information(response.status, " ", response.reason);
logger.information(response.contentType);
logger.information(response.content);
----
And here's the same example, with the request sent asynchronously:
var net = require('net');
var request = new net.HTTPRequest('GET', 'https://macchina.io');
var response = request.send(
function (result) {
if (result.error)
{
logger.error(result.error);
}
else
{
logger.information(result.response.status, " ", result.response.reason);
logger.information(result.response.contentType);
logger.information(result.response.content);
}
}
);
----
Of course, HTTPRequest can also be used to send POST or PUT requests, as well as
requests using any other HTTP methods.
Here's a sample how to post some JSON to a Hue base station to control a smart bulb:
var net = require('net');
var request = new net.HTTPRequest('PUT', 'http://192.168.178.151/api/newdeveloper/lights/1/state');
request.content = JSON.stringify({on: true, bri: 100, hue: 46920, sat: 255});
request.contentType = 'application/json';
request.timeout = 10.0;
request.send(
function(result)
{
if (result.error)
{
logger.error(result.error);
}
else
{
logger.information(result.response.status, " ", result.response.reason);
}
}
);
----
!!HTTPRequest Properties
HTTPRequest objects support the following properties:
!method (r/w)
The request method, e.g. "GET", "POST", etc.
!uri (r/w)
The request URI or path, e.g. "/index.html".
!version (r/w)
The HTTP version string, usually "HTTP/1.1".
!contentType (r/w)
The request content type, e.g. "application/json".
!content (r/w)
The request content, as string.
Only Unicode UTF-8 encoded text content is supported.
For other types of content, use the <[buffer]> property.
!buffer (r/w)
The request content, as Buffer object.
Using the <[buffer]> property, content that is not UTF-8 text can be handled.
Note: setting the <[buffer]> property will also affect the <[content]> property
(and vice-versa), since both use the same underlying data.
!timeout (r/w)
The request timeout in seconds.
!cookies (ro)
An object containing all cookies sent with the request, with cookie name
as key and cookie value as string value.
!headers (ro)
An object containing all header fields as properties. Note that the returned object
is not kept in sync with the request object. After making changes to the headers
in the request object headers (by calling `set`), query this property again to
receive an updated object.
!credentials (ro)
If the request has been sent with HTTP Basic Authentication information, returns
an object with a "username" and a "password" property containing the credentials.
If no valid authentication information has been sent, returns null.
!!HTTPRequest Methods
The following methods are supported by HTTPRequest objects:
!has(name)
Returns true if the request has a header with the given name, false otherwise.
!get(name [, default])
Returns the value of the request header with the given name, or the given default
value if the header is not present. If no default is given, returns an empty string
if the header is not present.
!set(name, value)
Sets the request header with the given name to the given value.
!authenticate(username, password)
Adds a HTTP Basic Authentication header to the request, using the given credentials.
!send([callback])
Sends the request. If a callback function is given, the function will return
immediately and will not return anything. Success or failure will be reported
via the callback function. The callback function must accept a single argument,
which will be an object containing an "error" or a "response" property.
If the request failed, the "error" property will contain an error message.
Otherwise, the "response" property will contain a HTTPResponse object.
Note that even if no "error" property is set, the request may still have
failed, although on the HTTP level. Check the HTTP response status,
using the <[result.response.status]> property.
If no callback function is given, the request is sent and the function will block
until the complete response is received, or an error has occurred. If an error occurred,
an exception will be raised. Otherwise, a HTTPResponse object will be returned.
!cancel()
Cancels an asynchronous request. Processing of the request will end and
the callback function passed to `send()` will not be called.
If `cancel()` is called after the request has already been completed, and
the callback function has been called, nothing happens.
!!HTTPResponse Properties
HTTPResponse object support the following properties:
!status (r/w)
The HTTP status code, e.g. 200.
!reason (r/w)
The HTTP status message, e.g. "OK" (for a 200 status).
!version (r/w)
The HTTP version string, e.g. "HTTP/1.1".
!contentType
The response body content type, e.g. "text/html".
!content (r/w)
The response content, as string.
Only Unicode UTF-8 encoded text content is supported.
For other types of content, use the <[buffer]> property.
!buffer (r/w)
The response content, as Buffer object.
Using the <[buffer]> property, content that is not UTF-8 text can be handled.
Note: setting the <[buffer]> property will also affect the <[content]> property
(and vice-versa), since both use the same underlying data.
!headers (ro)
An object containing all header fields as properties. Note that the returned object
is not kept in sync with the response object. After making changes to the headers
in the response object headers (by calling `set`), query this property again to
receive an updated object.
!!HTTPResponse Methods
!has(name)
Returns true if the response has a header with the given name, false otherwise.
!get(name [, default])
Returns the value of the response header with the given name, or the given default
value if the header is not present. If no default is given, returns an empty string
if the header is not present.
!set(name, value)
Sets the response header with the given name to the given value.
!setStatus(status)
Sets the response status code, e.g. 200.
!write(text) and writeln(text)
Appends text to the response body.
Note: currently only Unicode UTF-8 encoded text content is supported.
<[writeln()]> adds a newline after the text.
!writeHTML(text)
Writes text to the response body. All HTML reserved characters will be escaped properly.
!htmlize(text)
Returns a copy of text with all HTML reserved characters properly escaped.
!send()
Sends the response. Can be used in servlets or server pages on the global
<[response]> object only.
!sendFile(path [, contentType])
Sends the file given by path in the response, using the given `contentType`.
If no `contentType` is given, uses the one from the `contentType` property.
!redirect(location [, status])
Sends a redirect response with the given `location` in the `Location` header.
If no `status` is given, a 302 `Found` status is sent in the response, otherwise
the given status is used, which must be a valid 30x redirect status:
- 301 (Moved Permanently)
- 302 (Found)
- 303 (See Other)
- 307 (Temporary Redirect)
- 308 (Permanent Redirect)
!!!The form Object
The global <[form]> object is available in servlets and server pages. It gives
convenient access to any HTML form data sent by the browser.
The <[form]> object has two methods, <[has()]> and <[get()]>.
Additionally, the <[form]> object has shortcut accessors for form fields. Instead of writing:
const value = form.get('field');
----
one can also write:
const value = form.field;
----
!!form Methods
!has(name)
Returns true if the form has a field with the given name, false otherwise.
!get(name [, default])
Returns the value of the form field with the given name. If the field is not
present, returns the default value. If no default value has been given, returns
an empty string if the form field does not exist.
!!form Properties
!fields
This read-only property returns an object containing all form fields and their values
as properties.
!!!The uploads Array
The global <[uploads]> array is available in servlets and server pages. It gives
convenient access to any files uploaded through the browser via a HTML form
(with encoding type `multipart/form-data`).
For every file uploaded, the <[uploads]> array has an object providing information
about the file. The properties supported by these objects are described below.
Uploaded files can be accessed using the using the [[00205-MacchinaJSFileReference.html File]] API.
It is possible to specify a maximum size for uploaded files (in bytes), as well as the
maximum number of files uploaded with a single request in the `bundle.properties`
of the bundle containing the servlet or server page, with the `osp.js.maxUploadSize`
and `osp.js.maxUploadCount` properties e.g.:
osp.js.maxUploadSize = 262144
osp.js.maxUploadCount = 1
----
The default maximum upload size is 2 MBytes per file. If an uploaded file exdeeds the specified
maximum size, it will be ignored and a warning message will be written to the console.
The default maximum upload count is 4. If the number of uploaded files exceeds the specified
maximum count, these files will be ignored and a warning message will be printed to the console.
Note that uploaded files will be automatically deleted after the servlet or server page
finishes processing. If a servlet or server page wants to keep an uploaded file, it
should move or copy it to a different location, using the [[00205-MacchinaJSFileReference.html File]] API.
!!upload Properties
!path
The full path on the local filesystem the file has been stored to.
The uploaded file will be stored in the system's temporary file directory,
and will have a random unique file name.
!name
The name of the form element the file was uploaded through.
!filename
The original name of the uploaded file.
!contentType
The MIME type of the uploaded file, as reported by the browser in the part's
`Content-Type` header.
!size
The size of the uploaded file in bytes.
!headers
An object containing all part headers for the uploaded file sent by the browser,
e.g. `Content-Type` and `Content-Disposition`.
!!!The session Object
The global <[session]> object is available in servlets and server pages. It gives
access to the session object for the current request.
Note: Currently there is no way to create a session object from JavaScript.
In macchina.io EDGE, a session object is created when a user logs in to the web
interface.
!!session Properties
The <[session]> object supports the following read-only properties:
!id
The internal ID of the session object.
!username
The name of the signed-in user. Only available if a user is signed in and the session
is authenticated.
!authenticated
Returns true if the session is authenticated, otherwise false.
A session is authenticated if the user has successfully signed in.
!csrfToken
A random string that can be used as a CSRF synchronizer token in forms, to prevent
CSRF (Cross-Site Request Forgery) attacks.
!clientAddress
The IP address and port number of the HTTP client.
!!session Methods
!setInt(name, integer)
Adds or updates a an integer property with the given name to the session.
!getInt(name [, default])
Returns the integer value of the property with the given name.
!setBool(name, boolean)
Adds or updates a boolean property with the given name to the session.
!getBool(name [, default])
Returns the boolean value of the property with the given name.
!setString(name, string)
Adds or updates a string property with the given name to the session.
!getString(name [, default])
Returns the string value of the property with the given name.
!erase(name)
Erases the property with the given name.
!authorize(permission)
Returns true if the currently signed in user has the given permission, by
checking with the OSP authentication service, using the username from the
session.