-
Notifications
You must be signed in to change notification settings - Fork 586
/
Copy pathJsonPost.js
72 lines (64 loc) · 1.67 KB
/
JsonPost.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
/* Simple example of getting JSON from a POST */
const uWS = require('../dist/uws.js');
const port = 9001;
const app = uWS./*SSL*/App({
key_file_name: 'misc/key.pem',
cert_file_name: 'misc/cert.pem',
passphrase: '1234'
}).post('/*', (res, req) => {
/* Note that you cannot read from req after returning from here */
let url = req.getUrl();
/* Read the body until done or error */
readJson(res, (obj) => {
console.log('Posted to ' + url + ': ');
console.log(obj);
res.end('Thanks for this json!');
}, () => {
/* Request was prematurely aborted or invalid or missing, stop reading */
console.log('Invalid JSON or no data at all!');
});
}).listen(port, (token) => {
if (token) {
console.log('Listening to port ' + port);
} else {
console.log('Failed to listen to port ' + port);
}
});
/* Helper function for reading a posted JSON body */
function readJson(res, cb, err) {
let buffer;
/* Register data cb */
res.onData((ab, isLast) => {
let chunk = Buffer.from(ab);
if (isLast) {
let json;
if (buffer) {
try {
json = JSON.parse(Buffer.concat([buffer, chunk]));
} catch (e) {
/* res.close calls onAborted */
res.close();
return;
}
cb(json);
} else {
try {
json = JSON.parse(chunk);
} catch (e) {
/* res.close calls onAborted */
res.close();
return;
}
cb(json);
}
} else {
if (buffer) {
buffer = Buffer.concat([buffer, chunk]);
} else {
buffer = Buffer.concat([chunk]);
}
}
});
/* Register error cb */
res.onAborted(err);
}