Skip to content

Commit 24976c8

Browse files
Create JsonPost.js
1 parent a927d4b commit 24976c8

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

‎examples/JsonPost.js‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/* Simple example of getting JSON from a POST */
2+
3+
const uWS = require('../dist/uws.js');
4+
const port = 9001;
5+
6+
const app = uWS./*SSL*/App({
7+
key_file_name: 'misc/key.pem',
8+
cert_file_name: 'misc/cert.pem',
9+
passphrase: '1234'
10+
}).post('/*', (res, req) => {
11+
12+
/* Note that you cannot read from req after returning from here */
13+
let url = req.getUrl();
14+
15+
/* Read the body until done or error */
16+
readJson(res, (obj) => {
17+
console.log('Posted to ' + url + ': ');
18+
console.log(obj);
19+
20+
res.end('Thanks for this json!');
21+
}, () => {
22+
/* Request was prematurely aborted, stop reading */
23+
console.log('Ugh!');
24+
});
25+
26+
}).listen(port, (token) => {
27+
if (token) {
28+
console.log('Listening to port ' + port);
29+
} else {
30+
console.log('Failed to listen to port ' + port);
31+
}
32+
});
33+
34+
/* Helper function for reading a posted JSON body */
35+
function readJson(res, cb, err) {
36+
let buffer;
37+
/* Register data cb */
38+
res.onData((ab, isLast) => {
39+
let chunk = Buffer.from(ab);
40+
if (isLast) {
41+
if (buffer) {
42+
cb(JSON.parse(Buffer.concat([buffer, chunk])));
43+
} else {
44+
cb(JSON.parse(chunk));
45+
}
46+
} else {
47+
if (buffer) {
48+
buffer = Buffer.concat([buffer, chunk]);
49+
} else {
50+
buffer = Buffer.concat([chunk]);
51+
}
52+
}
53+
});
54+
55+
/* Register error cb */
56+
res.onAborted(err);
57+
}

0 commit comments

Comments
 (0)